Skip to content

Commit

Permalink
Create NumberOfEnclaves.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored May 24, 2024
1 parent a1c7bf9 commit 6a42758
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Graphs/NumberOfEnclaves.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// User function Template for C++

class Solution {
public:
int numberOfEnclaves(vector<vector<int>> &grid) {
// Code here
int n=grid.size(),m=grid[0].size();
vector<vector<int>>visited(n,vector<int>(m,0));
queue<pair<int,int>>q;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
// first row,first column,last row,last column
if(i==0 || j==0 || i==n-1 || j==m-1){
if(grid[i][j]==1){
q.push({i,j});
visited[i][j]=1;
}
}
}
}
int delrow[]={-1,0,+1,0};
int delcol[]={0,+1,0,-1};
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<n && ncol>=0 && ncol<m && visited[nrow][ncol]==0
&& grid[nrow][ncol]==1){
q.push({nrow,ncol});
visited[nrow][ncol]=1;
}
}
}
int cnt=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]==1 && visited[i][j]==0){
cnt++;
}
}
}
return cnt;
}
};

0 comments on commit 6a42758

Please sign in to comment.