题目链接
法一(DFS)
private int rowSize, colSize;
private void dfs(char[][] grid, int row, int col) {
if (row < 0 || row >= rowSize || col < 0 || col >= colSize || grid[row][col] == '0') {
return;
}
grid[row][col] = '0';
dfs(grid, row - 1, col);
dfs(grid, row, col + 1);
dfs(grid, row + 1, col);
dfs(grid, row, col - 1);
}
public int numIslands(char[][] grid) {
int landNum = 0;
rowSize = grid.length;
colSize = grid[0].length;
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < colSize; col++) {
if (grid[row][col] == '1') {
dfs(grid, row, col);
landNum++;
}
}
}
return landNum;
}
法二(BFS)
private int rowSize, colSize;
private int dirs[][] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
private Queue<Pair> queue = new LinkedList<>();
private static class Pair {
private int row, col;
private Pair(int row, int col) {
this.row = row;
this.col = col;
}
}
private void bfs(char[][] grid) {
while (!queue.isEmpty()) {
Pair now = queue.poll();
for (int[] dir : dirs) {
int nextRow = dir[0] + now.row;
int nextCol = dir[1] + now.col;
if (nextRow >= 0 && nextRow < rowSize && nextCol >= 0 && nextCol < colSize && grid[nextRow][nextCol] == '1') {
grid[nextRow][nextCol] = '0';
queue.offer(new Pair(nextRow, nextCol));
}
}
}
}
public int numIslands_2(char[][] grid) {
int landNum = 0;
rowSize = grid.length;
colSize = grid[0].length;
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < colSize; col++) {
if (grid[row][col] == '1') {
queue.offer(new Pair(row, col));
bfs(grid);
landNum++;
}
}
}
return landNum;
}
本地测试
lay.showTitle(200);
Solution200 sol200 = new Solution200();
char[][] grid200_1 = new char[][]{{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}};
char[][] grid200_2 = new char[][]{{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}};
arrayOpt.showCharTwoDimArray(grid200_1, grid200_1.length);
System.out.println(sol200.numIslands(grid200_1));
System.out.println(sol200.numIslands_2(grid200_2));