leetcode回顾——number-of-islands

题目

给定一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

输入:

11110
11010
11000
00000

输出: 1

示例 2:

输入:

11000
11000
00100
00011

输出: 3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

这道题其实可以用DFS或者BFS来做,DFS比较简单,因此这里二刷的时候,使用了BFS来AC这道题目

其大致的思想就是,从岛屿的其中一个点开始进行广度优先搜索,从与该点的邻点开始进行搜索,如果是岛屿的一部分,则标记已搜查过,如果不是,则跳过

AC代码

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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

public class NumIslands {

int nums = 0;
int[][] a = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
LinkedList<Node> queue = new LinkedList<>();
Set<Node> used = new HashSet<>();

public int numIslands(char[][] grid) {
int rows = grid.length;
if (rows == 0) {
return 0;
}
int cols = grid[0].length;
for (int row = 0; row < rows; row ++) {
for (int col = 0; col < cols; col ++) {
if (grid[row][col] == '1') {
bfs(grid, row, col, rows, cols);
nums += 1;
}
}
}
return nums;
}

public void bfs(char[][] grid, int row, int col, int rows, int cols) {
grid[row][col] = '2';
queue.clear();
used.clear();

Node root = new Node(row, col);
queue.add(root);
used.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
size --;
Node cur = queue.removeFirst();
int preX = cur.x;
int preY = cur.y;
for (int i = 0; i < a.length; i ++) {
int nX = preX + a[i][0];
int nY = preY + a[i][1];

if (nX < 0 || nY < 0 || nX >= rows || nY >= cols) {
continue;
}

if (grid[nX][nY] != '1') {
continue;
}

grid[nX][nY] = '2';

Node node = new Node(nX, nY);
if (!used.contains(node)) {
queue.add(node);
}
}
}
}
}

private static class Node {
int x;
int y;

Node(int x, int y) {
this.x = x;
this.y = y;
}

@Override
public boolean equals(Object o) {
Node t = (Node) o;
return x == t.x && y == t.y;
}

@Override
public int hashCode() {
return 1;
}
}

public static void main(String[] args) {
char[][] grid = new char[][]{
{'1','1','1','1','0'},
{'1','1','0','1','0'},
{'1','1','0','0','0'},
{'0','0','0','0','0'}
};
NumIslands nIslands = new NumIslands();
System.out.println(nIslands.numIslands(grid));
}

}