leetcode-200
LDK Lv5

leetcode-200 岛屿数量

标签:

  • DFS
  • BFS
  • UnionFind

思路:

三种思路:

  1. 使用DFS,从某个1开始搜索,标记所有搜索过的1为2(或者其他非1数值),直到找不到相邻的1,至此记为一个岛屿。循环遍历全图,即可得到岛屿数量。
  2. 使用BFS,原理同上
  3. 使用并查集。

题解代码:

并查集版本

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
class UnionFind {
public:
UnionFind(std::vector<std::vector<char>>& grid) {
this->count = 0;
int line = grid.size();
int column = grid[0].size();
for (int i = 0; i < line; ++i) {
for (int j = 0; j < column; ++j) {
if (grid[i][j] == '1') {
this->parent.push_back(i * column + j); // 祖宗等于自身
++this->count;
} else {
this->parent.push_back(-1); // 不属于并查集
}
rank.push_back(0);
}
}
}

int find(int i) {
if (parent[i] != i) // 祖宗节点不是自身,找祖宗节点
{
parent[i] = find(parent[i]);
}
return parent[i];
}

void unite(int x, int y) {
int rootx = find(x);
int rooty = find(y);
if (rootx != rooty) // 属于不同集,准备合并
{
if (rank[rootx] < rank[rooty]) // 确保 x 高度 >= y
{
swap(rootx, rooty);
}
parent[rooty] = rootx; // 将 y 挂在 x 下面
if (rank[rootx] == rank[rooty]) {
rank[rootx] += 1; // 如果合并前高度相等,合并后 x 高度 +1
}
--count;
}
}

int getCount() const { return this->count; }

int count;
std::vector<int> rank;
std::vector<int> parent;
};

class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int line = grid.size();
if (!line) {
return 0;
}
int column = grid[0].size();

UnionFind ufind(grid);
int num_islands = 0;
for (int i = 0; i < line; ++i) {
for (int j = 0; j < column; ++j) {
if (grid[i][j] == '1') {
grid[i][j] = '0';
if (i - 1 >= 0 && grid[i - 1][j] == '1') {
ufind.unite(i * column + j, (i - 1) * column + j);
}
if (j - 1 >= 0 && grid[i][j - 1] == '1') {
ufind.unite(i * column + j, i * column + j - 1);
}
if (i + 1 < line && grid[i + 1][j] == '1') {
ufind.unite(i * column + j, (i + 1) * column + j);
}
if (j + 1 < column && grid[i][j + 1] == '1') {
ufind.unite(i * column + j, i * column + j + 1);
}
}
}
}
return ufind.getCount();
}
};
由 Hexo 驱动 & 主题 Keep
本站由 提供部署服务
总字数 101.7k 访客数 访问量