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 38 39 40 41 42 43 44 45
| class Solution {
private static final int[][] DIRECTIONS = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private static class State { private boolean closed = true; }
public int closedIsland(int[][] grid) { int m = grid.length, n = grid[0].length;
int closedIslands = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0) { State state = new State(); dfs(state, grid, i, j); if (state.closed) { closedIslands++; } } } }
return closedIslands; }
private void dfs(State state, int[][] grid, int i, int j) { int m = grid.length, n = grid[0].length;
grid[i][j] = 2;
for (int[] direction : DIRECTIONS) { int nextI = i + direction[0], nextJ = j + direction[1]; if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n) { if (grid[nextI][nextJ] == 0) { dfs(state, grid, nextI, nextJ); } } else { state.closed = false; } } } }
|