-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode-NumberOfClsoedIslands.cpp
66 lines (46 loc) · 2.16 KB
/
LeetCode-NumberOfClsoedIslands.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
struct pair_hash {
inline std::size_t operator()(const std::pair<int,int> & v) const {
int a = v.first;
int b = v.second;
return a >= b ? a * a + a + b : a + b * b;
}
};
class Solution {
public:
int closedIsland(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
int count = 0;
unordered_set<pair<int, int>, pair_hash> visited;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 1) continue;
if (visited.count({i, j}) <= 0) {
bool valid = true;
stack<pair<int, int>> s;
s.push({i, j});
while (!s.empty()) {
pair<int, int> u = s.top();
s.pop();
if (visited.count(u) <= 0) {
if (u.first == 0 || u.first == n - 1 || u.second == 0 || u.second == m - 1) {
valid = false;
}
visited.insert(u);
vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
for (const auto& dir : directions) {
pair<int, int> v = {u.first + dir.first, u.second + dir.second};
if (v.first < 0 || v.first >= n || v.second < 0 || v.second >= m) continue;
if (grid[v.first][v.second] == 0) {
s.push({v.first, v.second});
}
}
}
}
if (valid) ++count;
}
}
}
return count;
}
};