-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberOfEnclaves.cpp
50 lines (45 loc) · 1.62 KB
/
NumberOfEnclaves.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
class Solution {
public:
int numEnclaves(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> vis(m, vector<int>(n, 0));
queue<pair<int, int>> q;
// Mark all boundary land cells and start BFS from them
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == m-1 || j == n-1) {
if (grid[i][j] == 1) {
q.push({i, j});
vis[i][j] = 1;
}
}
}
}
// Directions array for traversing up, down, left, right
int delRow[] = {-1, 0, 1, 0};
int delCol[] = {0, -1, 0, 1};
// BFS to mark all reachable land cells from the boundary
while (!q.empty()) {
int row = q.front().first;
int col = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int nrow = row + delRow[i];
int ncol = col + delCol[i];
if (nrow >= 0 && nrow < m && ncol >= 0 && ncol < n && !vis[nrow][ncol] && grid[nrow][ncol] == 1) {
q.push({nrow, ncol});
vis[nrow][ncol] = 1;
}
}
}
// Count all unvisited land cells which are enclaved
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1 && vis[i][j] == 0) count++;
}
}
return count;
}
};