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
| class Solution { int[][] dirs = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; public int numEnclaves(int[][] A) { int ans = 0;
for (int row = 0; row < A.length; row++) { for (int col = 0; col < A[0].length; col++) { if (isBoundary(A, row, col) && A[row][col] == 1) { dfs(A, row, col); } } } for (int row = 0; row < A.length; row++) for (int col = 0; col < A[0].length; col++) if(A[row][col] == 1) ans++; return ans; } private void dfs(int[][] A, int row, int col) { if (outOfBoundary(A, row, col) || A[row][col] == 0 || A[row][col] == -1) return; A[row][col] = -1; for (int[] dir : dirs) { dfs(A, row + dir[0], col + dir[1]); } } private boolean isBoundary(int[][] A, int row, int col) { return row == 0 || row == A.length - 1 || col == 0 || col == A[0].length - 1; } private boolean outOfBoundary(int[][] A, int row, int col) { return row < 0 || row > A.length - 1 || col < 0 || col > A[0].length - 1; } }
|