-
Notifications
You must be signed in to change notification settings - Fork 1
/
1254_number_of_closed_islands.cpp
57 lines (49 loc) · 1.48 KB
/
1254_number_of_closed_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
#include<bits/stdc++.h>
using namespace std;
/*
1254. Number of Closed Islands
Medium
3.8K
128
Companies
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
NO IDEA:) except BFS and DFS
*/
class Solution {
public:
int closedIsland(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int count = 0;
vector<vector<bool>> visit(m, vector<bool>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0 && !visit[i][j] && dfs(i, j, m, n, grid, visit)) {
count++;
}
}
}
return count;
}
bool dfs(int x, int y, int m, int n, vector<vector<int>>& grid, vector<vector<bool>>& visit) {
if (x < 0 || x >= m || y < 0 || y >= n) {
return false;
}
if (grid[x][y] == 1 || visit[x][y]) {
return true;
}
visit[x][y] = true;
bool isClosed = true;
vector<int> dirx {0, 1, 0, -1};
vector<int> diry {-1, 0, 1, 0};
for (int i = 0; i < 4; i++) {
int r = x + dirx[i];
int c = y + diry[i];
if (!dfs(r, c, m, n, grid, visit)) {
isClosed = false;
}
}
return isClosed;
}
};