-
Notifications
You must be signed in to change notification settings - Fork 0
/
200_numberOfIslands.cpp
138 lines (114 loc) · 2.98 KB
/
200_numberOfIslands.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
127
128
129
130
131
132
133
134
135
136
137
138
#include <iostream>
#include <vector>
using namespace std;
class UnionFind
{
public:
void initialise(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
count = 0;
for (int i = 0; i != m; ++i) {
for (int j = 0; j != n; ++j) {
if ('1' == grid[i][j]) {
count++;
roots.push_back(i * n + j);
}
else {
roots.push_back(0);
}
}
}
}
int findRoot(int i) {
int root = i;
while (root != roots[root]) {
root = roots[root];
}
// Optimise: path compress
while (root != roots[i]) {
int tmp = roots[i];
roots[i] = root;
i = tmp;
}
return root;
}
bool isConnected(int p, int q) {
return findRoot(p) == findRoot(q);
}
void unionRoot(int p, int q) {
int rootP = findRoot(p);
int rootQ = findRoot(q);
if (rootP == rootQ)
return;
roots[rootP] = rootQ;
count--;
}
int getCount() {
return count;
}
private:
vector<int> roots;
int count;
};
vector<int> dx = {0, 0, -1, 1};
vector<int> dy = {-1, 1, 0, 0};
bool isValid(vector<vector<char>>& grid, int row, int col)
{
return (row >=0 && row < grid.size() && col >= 0 && col < grid[0].size() && '1' == grid[row][col]);
}
int infect(vector<vector<char>>& grid, int row, int col)
{
if (isValid(grid, row, col)) {
grid[row][col] = '0';
for (int i = 0; i != 4; ++i) {
infect(grid, row + dx[i], col + dy[i]);
}
return 1;
}
return 0;
}
int numIslands(vector<vector<char>>& grid) {
// floodFill
// int count = 0;
// for (int i = 0; i != grid.size(); ++i) {
// for(int j = 0; j != grid[i].size(); ++j) {
// count += infect(grid, i, j);
// }
// }
int m = grid.size();
if (m < 1) return 0;
int n = grid[0].size();
if (n < 1) return 0;
UnionFind uf;
uf.initialise(grid);
for (int i = 0; i != m; ++i) {
for (int j = 0; j != n; ++j) {
if (grid[i][j] == '0') {
continue;
}
for (int k = 0; k !=4; ++k) {
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >=0 && newY >= 0 && newX < m && newY < n && grid[newX][newY] == '1') {
uf.unionRoot(i * n + j, newX * n + newY);
}
}
}
}
return uf.getCount();
}
int main(int argc, char const *argv[])
{
vector<vector<char>> grid = {
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '1', '0'}
};
int ret = numIslands(grid);
cout << "result = " << ret << endl;
return 0;
}