我正在创建一个方法,它接受一个二维数组并扫描整个数组以查找被零完全包围的数字“块”,并将这些块(我称之为岛屿)转换为零。
我试图删除除最大岛屿外的所有“岛屿”。
例如,对于这个二维数组:
在这种情况下,岛屿。
我试图删除除最大岛屿外的所有“岛屿”。
例如,对于这个二维数组:
1 2 3 2 2 1
3 2 2 1 2 3
3 2 2 1 3 2
2 3 2 3 2 2
2 2 3 1 1 2
3 2 1 2 3 2
2 3 1 2 3 2
2 2 0 0 0 0
0 0 0 1 2 0
0 0 0 0 0 0
在这个方法之后,2D数组应该是这样的:
1 2 3 2 2 1
3 2 2 1 2 3
3 2 2 1 3 2
2 3 2 3 2 2
2 2 3 1 1 2
3 2 1 2 3 2
2 3 1 2 3 2
2 2 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
小片段1 2
被"删除"
这是第二个例子,因为该方法应该将不属于“主”片段的数字块和位于边缘的岛作为单独的块来处理。
原始数组如下:
1 2 3 2 2 1
3 2 2 1 2 3
3 2 2 1 3 2
2 3 2 3 2 2
2 2 3 1 1 2
3 2 1 2 3 2
2 3 1 2 3 2
2 2 0 0 0 0
0 0 0 1 2 3
0 0 0 0 3 2
方法执行后,应该是这样的:
1 2 3 2 2 1
3 2 2 1 2 3
3 2 2 1 3 2
2 3 2 3 2 2
2 2 3 1 1 2
3 2 1 2 3 2
2 3 1 2 3 2
2 2 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
在这种情况下,岛屿。
1 2 3
3 2
被删除的原因是它与大块分开,被零包围。
以下是我目前拥有的代码,但它并没有按预期工作。这是错误的,因为我认为它将主要块视为孤岛,结果是将整个数组转换为零,而不仅仅是删除小的孤岛。它包括一个示例,当您运行它时,您应该看到它的效果。
public class destroyIslands {
public static void main(String[] args) {
int[][] example = { {1, 2, 3, 1, 2},
{2, 3, 2, 1, 2},
{3, 2, 1, 2, 2},
{0, 2, 0, 0, 0},
{0, 0, 0, 2, 1} };
example = deleteIslandBoard(example);
printGrid(example);
}
public static int[][] deleteIslandBoard(int[][] array) {
// Create a boolean array to track which cells have been visited
boolean[][] visited = new boolean[array.length][array[0].length];
// Iterate
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
// If the cell is not visited and is part of an island
if (!visited[i][j] && array[i][j] != 0) {
// Delete the island by setting all cells to 0
deleteIsland(array, i, j, visited);
}
}
}
// Return the modified array
return array;
}
public static void deleteIsland(int[][] array, int i, int j, boolean[][] visited) {
// Check if the current cell is out of board or if it has already been visited
if (i < 0 || i >= array.length || j < 0 || j >= array[0].length || visited[i][j]) {
return;
}
// Mark the current cell as visited
visited[i][j] = true; // If the current cell is part of the island, set it to 0
if (array[i][j] != 0) {
array[i][j] = 0;
// Recursively delete the neighboring cells that are part of the island
deleteIsland(array, i - 1, j, visited);
deleteIsland(array, i + 1, j, visited);
deleteIsland(array, i, j - 1, visited);
deleteIsland(array, i, j + 1, visited);
}
}
public static void printGrid(int[][] grid) {
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}
}
你有什么想法需要改变吗?