-
Notifications
You must be signed in to change notification settings - Fork 0
/
number_of_islands.cpp
128 lines (113 loc) · 2.61 KB
/
number_of_islands.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
// =====================================================================================
//
// Filename: number_of_islands.cpp
//
// Description: 200. Number of Islands.
//
// Version: 1.0
// Created: 09/12/2019 01:20:27 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <vector>
class UnionFind
{
public:
UnionFind(int count): count_(count)
{
buf_ = new int[count];
for (int i = 0; i < count; i++)
{
buf_[i] = i;
}
}
virtual ~UnionFind()
{
delete[] buf_;
buf_ = nullptr;
}
int find(int idx) const
{
while (buf_[idx] != idx)
{
idx = buf_[idx];
}
return idx;
}
void connect(int a, int b)
{
int i = find(a);
int j = find(b);
if (i == j)
{
return;
}
buf_[i] = j;
count_ -= 1;
}
bool isConnected(int a, int b) const
{
return find(a) == find(b);
}
int getCount() const
{
return count_;
}
private:
int count_ = 0;
int* buf_ = nullptr;
};
class Solution
{
public:
int numIslands(std::vector<std::vector<char>>& grid)
{
if (grid.size() == 0 || grid[0].size() == 0)
{
return 0;
}
int m = grid.size();
int n = grid[0].size();
UnionFind uf(m * n);
int zeros = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (grid[i][j] != '1')
{
zeros++;
continue;
}
if (j > 0 && grid[i][j - 1] == '1')
{
// Connect current and left node
uf.connect(i * n + j, i * n + j - 1);
}
if (i > 0 && grid[i - 1][j] == '1')
{
// Connect current and upper node
uf.connect(i * n + j, (i - 1) * n + j);
}
}
}
return (uf.getCount() - zeros);
}
};
int main(int argc, char* argv[])
{
std::vector<std::vector<char>> grid = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'},
};
int num = Solution().numIslands(grid);
printf("num = %d\n", num);
return 0;
}