Skip to content

Instantly share code, notes, and snippets.

@fpdjsns
Created April 8, 2019 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fpdjsns/91d296e10a828da48b4751a9fad00080 to your computer and use it in GitHub Desktop.
Save fpdjsns/91d296e10a828da48b4751a9fad00080 to your computer and use it in GitHub Desktop.
[leetcode] 1020. Number of Enclaves : https://leetcode.com/problems/number-of-enclaves/
class Solution {
private:
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
public:
int getAnswer(int x, int y, vector<vector<int>>& A){
int r = A.size();
int c = A[0].size();
bool isAns = true;
queue<pair<int,int>> q;
q.push({x, y});
A[x][y] = 0;
int cnt = 0;
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
cnt++;
for(int i=0;i<4;i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || r <= nx || ny < 0 || c <= ny){
isAns = false;
continue;
}
if(A[nx][ny] == 0) continue;
q.push({nx,ny});
A[nx][ny] = 0;
}
}
return isAns ? cnt : 0;
}
int numEnclaves(vector<vector<int>>& A) {
int answer = 0;
for(int i=0;i<A.size();i++){
for(int j=0;j<A[i].size();j++){
if(A[i][j] == 1)
answer += getAnswer(i,j,A);
}
}
return answer;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment