1020. Number of Enclaves
Solution
DFS all edges first to let the node connecting to the edge become 0.
Then check how many node[i][j] left, which node[i][j] == 1
public int numEnclaves(int[][] A) {
int M = A.length;
int N = A[0].length;
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){
dfs(A, i, j);
}
}
}
int count = 0;
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
if(A[i][j] == 1)
count++;
}
}
return count;
}
public void dfs(int[][] A, int i, int j){
int M = A.length;
int N = A[0].length;
if(i < 0 || i >= M || j < 0 || j >= N || A[i][j] == 0) return;
A[i][j] = 0;
int[][] dirs = new int[][]{{0,1}, {1,0}, {0,-1}, {-1,0}};
for(int[] dir : dirs){
dfs(A, i+dir[0], j+dir[1]);
}
}
Last updated
Was this helpful?