-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNumber of closed islands
37 lines (36 loc) · 969 Bytes
/
Number of closed islands
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
class Solution {
public int closedIsland(int[][] grid) {
int m=grid.length;
int n=grid[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0||i==m-1||j==0||j==n-1){
if(grid[i][j]==0){
dfs(i,j,grid,m,n);
}
}
}
}
int answer=0;
for(int i=1;i<m-1;i++){
for(int j=1;j<n-1;j++){
if(grid[i][j]==0){
dfs(i,j,grid,m,n);
answer++;
}
}
}
return answer;
}
private void dfs(int cr,int cc,int[][] grid,int m,int n){
if(cr<0||cr>=m||cc<0||cc>=n||grid[cr][cc]!=0){
return;
}
grid[cr][cc]=1;
dfs(cr-1,cc,grid,m,n);
dfs(cr+1,cc,grid,m,n);
dfs(cr,cc-1,grid,m,n);
dfs(cr,cc+1,grid,m,n);
return;
}
}