Skip to content

Commit 9a3fcff

Browse files
authored
Create Count Islands With Total Value Divisible by K.java
1 parent af947de commit 9a3fcff

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy