LeetCode——岛屿数量
Q:给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
A:用来练手的,BFS和DFS
public static int numIslands(char[][] grid) {
if (grid.length == 0)
return 0;
int num = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
// DFS(grid, i, j);
BFS(grid, i, j);
num++;
}
}
}
return num;
}
private static void BFS(char[][] grid, int i, int j) {
Queue<Pair<Integer, Integer>> q = new LinkedList<>();
q.add(new Pair<>(i, j));
grid[i][j] = '0';
while (!q.isEmpty()) {
Pair<Integer, Integer> p = q.poll();
int x = p.getKey();
int y = p.getValue();
if (x - 1 >= 0 && grid[x - 1][y] == '1') {
q.add(new Pair<>(x - 1, y));
grid[x - 1][y] = '0';
}
if (x + 1 < grid.length && grid[x + 1][y] == '1') {
q.add(new Pair<>(x + 1, y));
grid[x + 1][y] = '0';
}
if (y - 1 >= 0 && grid[x][y - 1] == '1') {
q.add(new Pair<>(x, y - 1));
grid[x][y - 1] = '0';
}
if (y + 1 < grid[0].length && grid[x][y + 1] == '1') {
q.add(new Pair<>(x, y + 1));
grid[x][y + 1] = '0';
}
}
}
private static void DFS(char[][] grid, int i, int j) {
grid[i][j] = '0';
if (i - 1 >= 0 && grid[i - 1][j] == '1')
DFS(grid, i - 1, j);
if (i + 1 < grid.length && grid[i + 1][j] == '1')
DFS(grid, i + 1, j);
if (j - 1 >= 0 && grid[i][j - 1] == '1')
DFS(grid, i, j - 1);
if (j + 1 < grid[0].length && grid[i][j + 1] == '1')
DFS(grid, i, j + 1);
}