|
| 1 | +class Solution { |
| 2 | + |
| 3 | + private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; |
| 4 | + |
| 5 | + public int countIslands(int[][] grid, int k) { |
| 6 | + int rows = grid.length; |
| 7 | + int cols = grid[0].length; |
| 8 | + boolean[][] visited = new boolean[rows][cols]; |
| 9 | + int count = 0; |
| 10 | + for (int i = 0; i < rows; i++) { |
| 11 | + for (int j = 0; j < cols; j++) { |
| 12 | + if (grid[i][j] != 0 && !visited[i][j]) { |
| 13 | + int[] value = {0}; |
| 14 | + traverse(grid, i, j, visited, value); |
| 15 | + if (value[0] % k == 0) { |
| 16 | + count++; |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + return count; |
| 22 | + } |
| 23 | + |
| 24 | + private void traverse(int[][] grid, int row, int col, boolean[][] visited, int[] value) { |
| 25 | + if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length || visited[row][col] || grid[row][col] == 0) { |
| 26 | + return; |
| 27 | + } |
| 28 | + visited[row][col] = true; |
| 29 | + value[0] += grid[row][col]; |
| 30 | + for (int[] dir : DIRECTIONS) { |
| 31 | + traverse(grid, row + dir[0], col + dir[1], visited, value); |
| 32 | + } |
| 33 | + } |
| 34 | +} |
0 commit comments