Skip to content

Commit 51d4e1a

Browse files
committed
1254. Number of Closed Islands(amend commit msg test)
1 parent 9fb2af3 commit 51d4e1a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.gatsby;
2+
3+
public class _1254NumberOfClosedIslands {
4+
private int[][] isVisited;
5+
int row;
6+
int col;
7+
int res;
8+
9+
private boolean dfs(int i, int j) {
10+
if (i < 0 || j < 0 || i >= row || j >= col) return false; // 和边界接壤,实际上不属于被包围
11+
if (isVisited[i][j] == 1) return true;
12+
isVisited[i][j] = 1;
13+
// 不能使用&&因为我们需要在每一次遍历中都把所有的格子都标记,但是如果使用&&,一旦前提条件不符合,后面的dfs就不会执行了
14+
return dfs(i - 1, j) & dfs(i, j - 1) & dfs(i + 1, j) & dfs(i, j + 1);
15+
}
16+
17+
18+
public int closedIsland(int[][] grid) {
19+
this.row = grid.length;
20+
this.col = grid[0].length;
21+
this.isVisited = grid;
22+
for (int i = 0; i < row; ++i) {
23+
for (int j = 0; j < col; ++j) {
24+
if (isVisited[i][j] == 0 && dfs(i, j))
25+
res++;
26+
}
27+
}
28+
return res;
29+
}
30+
}

0 commit comments

Comments
 (0)