Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110 11010 11000 00000
Answer: 1
Example 2:
11000 11000 00100 00011
Answer: 3
分析
这道题思路比较直接,显然就是从值为‘1’的点BFS或DFS,访问过的点做标记,直到搜索结束,一共可以进行几次搜索就意味着有多少个Islands.
至于对访问的点做标记,我们可以用一个boolean数组标记,如果可以修改原数组的话,我们也可以直接把访问过的原先是‘1’的点改成‘0’来标记已访问即可。我写的代码是用后者。
复杂度
BFS: time: O(n), space: O(n)
DFS: time: O(n), space: O(h)
这里n表示值为‘1’的点的个数,h表示DFS深度
代码
- DFS
public class Solution {
public int numIslands(char[][] grid) {
int rows = grid.length;
if (rows == 0) {
return 0;
}
int cols = grid[0].length;
int res = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
res++;
dfs(grid, i, j);
}
}
}
return res;
}
private void dfs(char[][] grid, int row, int col) {
if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] == '0') {
return;
}
// 访问过的做标记
grid[row][col] = '0';
// 搜邻居
dfs(grid, row - 1, col);
dfs(grid, row + 1, col);
dfs(grid, row, col - 1);
dfs(grid, row, col + 1);
}
}
- BFS
public class Solution {
public int numIslands(char[][] grid) {
int rows = grid.length;
if (rows == 0) {
return 0;
}
int cols = grid[0].length;
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
count++;
bfs(grid, i, j);
}
}
}
return count;
}
private void bfs(char[][] grid, int row, int col) {
Queue<int[]> q = new LinkedList<int[]>();
int[][] dirs = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
q.add(new int[]{row, col});
grid[row][col] = '0';
while (!q.isEmpty()) {
int[] top = q.remove();
for (int i = 0; i < dirs.length; i++) {
int x = dirs[i][0] + top[0];
int y = dirs[i][1] + top[1];
if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length) {
if (grid[x][y] == '1') {
grid[x][y] = '0';
q.add(new int[]{x, y});
}
}
}
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。