[leetcode] problem 200 – 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

No.1

Input:

1
2
3
4
11110
11010
11000
00000

Output: 1

No.2

Input:

1
2
3
4
11000
11000
00100
00011

Output: 3

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public int (char[][] grid) {
int count = 0;

if (grid == null || grid.length < 1 || grid[0].length < 1)
return count;

int n = grid.length;
int m = grid[0].length;
boolean[][] visit = new boolean[n][m];

for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1' && !visit[i][j]) {
bfs(grid, visit, i, j);
count++;
}
}
}

return count;
}

private void bfs(char[][] grid, boolean[][] visit, int i, int j) {
int n = grid.length;
int m = grid[0].length;
int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[] {i, j});
visit[i][j] = true;

while (!queue.isEmpty()) {
int[] position = queue.poll();

for (int[] direction : directions) {
int x = position[0] + direction[0];
int y = position[1] + direction[1];

if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == '1' && !visit[x][y]) {
visit[x][y] = true;
queue.offer(new int[] {x, y});
}
}
}
}