LeetCode 200 - Number of Islands - 题解/Solution

https://leetcode.com/problems/number-of-islands/

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* 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
*
* @author dongyuxi
*
*/
public class Solution {
public int numIslands(char[][] grid) {
if (null == grid || 0 == grid.length || 0 == grid[0].length) {
return 0;
}
int row = grid.length;
int col = grid[0].length;
int island = 0;
boolean[][] visited = new boolean[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '1' && !visited[i][j]) {
island++;
Queue<Integer> rowQueue = new LinkedList<Integer>();
Queue<Integer> colQueue = new LinkedList<Integer>();
rowQueue.add(i);
colQueue.add(j);
while (!rowQueue.isEmpty()) {
int topRow = rowQueue.poll();
int topCol = colQueue.poll();
if (topRow - 1 >= 0 && grid[topRow - 1][topCol] == '1' && !visited[topRow - 1][topCol]) {
rowQueue.add(topRow - 1);
colQueue.add(topCol);
visited[topRow - 1][topCol] = true;
}
if (topRow + 1 < row && grid[topRow + 1][topCol] == '1' && !visited[topRow + 1][topCol]) {
rowQueue.add(topRow + 1);
colQueue.add(topCol);
visited[topRow + 1][topCol] = true;
}
if (topCol - 1 >= 0 && grid[topRow][topCol - 1] == '1' && !visited[topRow][topCol - 1]) {
rowQueue.add(topRow);
colQueue.add(topCol - 1);
visited[topRow][topCol - 1] = true;
}
if (topCol + 1 < col && grid[topRow][topCol + 1] == '1' && !visited[topRow][topCol + 1]) {
rowQueue.add(topRow);
colQueue.add(topCol + 1);
visited[topRow][topCol + 1] = true;
}
}
}
}
}
return island;
}
}


支付宝 微信
文章目录