-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-200.cpp
More file actions
68 lines (65 loc) · 1.87 KB
/
LeetCode-200.cpp
File metadata and controls
68 lines (65 loc) · 1.87 KB
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
/*************************************************************************
> File Name: LeetCode-200.cpp
> Author: ltw
> Mail: 3245849061@qq.com
> Created Time: Thu 21 May 2020 08:58:56 PM CST
************************************************************************/
#include <iostream>
using namespace std;
class Solution {
public:
struct UnionSet {
int *fa, *cnt;
UnionSet(int n) {
fa = new int[n + 1];
cnt = new int[n + 1];
for (int i = 0; i <= n; i++) {
fa[i] = i;
cnt[i] = 1;
}
}
bool isroot(int x) {
return x == fa[x];
}
int get(int x) {
return (fa[x] = (x == fa[x] ? x : get(fa[x])));
}
void merge(int a, int b) {
int aa = get(a), bb = get(b);
if (aa == bb) return ;
fa[aa] = bb;
cnt[bb] += cnt[aa];
return ;
}
~UnionSet() {
delete[] fa;
delete[] cnt;
}
};
int n, m;
int ind(int i, int j) {
return (i * m) + j + 1;
}
int numIslands(vector<vector<char>>& grid) {
if (grid.size() == 0) return 0;
n = grid.size();
m = grid[0].size();
UnionSet u(n * m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '0') continue;
if (i && grid[i - 1][j] == '1') u.merge(ind(i, j), ind(i - 1, j));
if (j && grid[i][j - 1] == '1') u.merge(ind(i, j), ind(i, j - 1));
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '0') continue;
if (!u.isroot(ind(i, j))) continue;
ans += 1;
}
}
return ans;
}
};