-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathno_of_enclaves_bfs.cpp
68 lines (59 loc) · 1.75 KB
/
no_of_enclaves_bfs.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
#include <bits/stdc++.h>
using namespace std;
/*
Link: https://leetcode.com/problems/number-of-enclaves/
Video link: https://youtu.be/rxKcepXQgU4
*/
class Solution
{
public:
int numEnclaves(vector<vector<int>> &grid)
{
queue<pair<int, int>> q;
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> visited(n, vector<int>(m, 0));
// rather traversing each boundary indivodually
// traverse entire matrix and apply specific condition
for (int r = 0; r < n; r++){
for (int c = 0; c < m; c++) {
if (r == 0 || c == 0 || r == n - 1 || c == m - 1)
{
if (grid[r][c] == 1)
{
q.push({r, c});
visited[r][c] = 1;
}
}
}
}
int delta_row[] = {-1, 0, 1, 0};
int delta_col[] = {0, 1, 0, -1};
while(!q.empty())
{
int r = q.front().first;
int c = q.front().second;
q.pop();
for (int i = 0; i < 4; i++){
int nrow = r + delta_row[i];
int ncol = c + delta_col[i];
if(nrow >= 0 and nrow < n and ncol >= 0 and ncol < m)
{
if(!visited[nrow][ncol] and grid[nrow][ncol])
{
q.push({nrow, ncol});
visited[nrow][ncol] = 1;
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if(grid[i][j] and !visited[i][j])
++ans;
}
}
return ans;
}
};