forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain4.cpp
126 lines (102 loc) · 2.78 KB
/
main4.cpp
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/// Source : https://leetcode.com/problems/number-of-islands/description/
/// Author : liuyubobobo
/// Time : 2018-08-26
#include <iostream>
#include <vector>
#include <cassert>
#include <unordered_set>
using namespace std;
/// Using union-find
/// Time Complexity: O(n*m)
/// Space Complexity: O(n*m)
class UnionFind{
private:
vector<int> rank, parent;
public:
UnionFind(int n){
rank.clear();
parent.clear();
for( int i = 0 ; i < n ; i ++ ){
parent.push_back(i);
rank.push_back(1);
}
}
int find(int p){
while(p != parent[p]){
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
bool isConnected(int p , int q){
return find(p) == find(q);
}
void unionElements(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
if(pRoot == qRoot)
return;
if(rank[pRoot] < rank[qRoot])
parent[pRoot] = qRoot;
else if(rank[qRoot] < rank[pRoot])
parent[qRoot] = pRoot;
else{ // rank[pRoot] == rank[qRoot]
parent[pRoot] = qRoot;
rank[qRoot] += 1;
}
}
};
class Solution {
private:
int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int m, n;
public:
int numIslands(vector<vector<char>>& grid) {
m = grid.size();
if(m == 0)
return 0;
n = grid[0].size();
if(n == 0)
return 0;
UnionFind uf(m * n);
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
if(grid[i][j] == '1')
for(int k = 0; k < 4; k ++){
int newX = i + d[k][0];
int newY = j + d[k][1];
if(inArea(newX, newY) && grid[newX][newY] == '1')
uf.unionElements(i * n + j, newX * n + newY);
}
unordered_set<int> regions;
for(int i = 0 ; i < m; i ++)
for(int j = 0; j < n; j ++)
if(grid[i][j] == '1')
regions.insert(uf.find(i * n + j));
return regions.size();
}
private:
bool inArea(int x, int y){
return x >= 0 && x < m && y >= 0 && y < n;
}
};
int main() {
vector<vector<char>> grid1 = {
{'1','1','1','1','0'},
{'1','1','0','1','0'},
{'1','1','0','0','0'},
{'0','0','0','0','0'}
};
cout << Solution().numIslands(grid1) << endl;
// 1
// ---
vector<vector<char>> grid2 = {
{'1','1','0','0','0'},
{'1','1','0','0','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'}
};
cout << Solution().numIslands(grid2) << endl;
// 3
return 0;
}