200 Number of Islands

1. Question

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:
1
11110
2
11010
3
11000
4
00000
Copied!
Answer: 1
Example 2:
1
11000
2
11000
3
00100
4
00011
Copied!
Answer: 3

2. Implementation

(1) BFS
1
class Solution {
2
public int numIslands(char[][] grid) {
3
if (grid == null || grid.length == 0) {
4
return 0;
5
}
6
7
int[][] directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
8
int m = grid.length, n = grid[0].length;
9
int count = 0;
10
11
for (int i = 0; i < m; i++) {
12
for (int j = 0; j < n; j++) {
13
if (grid[i][j] == '1') {
14
++count;
15
searchByBFS(grid, i, j, m, n, directions);
16
}
17
}
18
}
19
return count;
20
}
21
22
public void searchByBFS(char[][] grid, int row, int col, int m, int n, int[][] directions) {
23
grid[row][col] = '0';
24
25
Queue<Integer> queue = new LinkedList<>();
26
queue.add(row * n + col);
27
28
while (!queue.isEmpty()) {
29
int curPoint = queue.remove();
30
int curRow = curPoint / n;
31
int curCol = curPoint % n;
32
33
for (int[] direction : directions) {
34
int nextRow = curRow + direction[0];
35
int nextCol = curCol + direction[1];
36
37
if (isValid(grid, nextRow, nextCol)) {
38
grid[nextRow][nextCol] = '0';
39
queue.add(nextRow * n + nextCol);
40
}
41
}
42
}
43
}
44
45
public boolean isValid(char[][] grid, int row, int col) {
46
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == '1';
47
}
48
}
Copied!
(2) DFS
1
class Solution {
2
public int numIslands(char[][] grid) {
3
if (grid == null || grid.length == 0 || grid[0].length == 0) {
4
return 0;
5
}
6
7
int m = grid.length, n = grid[0].length;
8
int count = 0;
9
10
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
11
12
for (int i = 0; i < m; i++) {
13
for (int j = 0; j < n; j++) {
14
if (grid[i][j] == '1') {
15
++count;
16
searchIslandByDFS(i, j, grid, directions);
17
}
18
}
19
}
20
return count;
21
}
22
23
public void searchIslandByDFS(int row, int col, char[][] grid, int[][] directions) {
24
grid[row][col] = '0';
25
26
for (int[] direction : directions) {
27
int nextRow = row + direction[0];
28
int nextCol = col + direction[1];
29
30
if (isValid(nextRow, nextCol, grid)) {
31
searchIslandByDFS(nextRow, nextCol, grid, directions);
32
}
33
}
34
}
35
36
public boolean isValid(int row, int col, char[][] grid) {
37
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == '1';
38
}
39
}
Copied!

3. Time & Space Complexity

BFS: 时间复杂度O(mn), 空间复杂度:O(mn)
DFS: 时间复杂度O(mn), 空间复杂度:O(mn)