Skip to content

Commit 1c4f6a5

Browse files
authored
Create Count Sub Islands.java
1 parent ca2f908 commit 1c4f6a5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Medium/Count Sub Islands.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
private final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
3+
4+
public int countSubIslands(int[][] grid1, int[][] grid2) {
5+
int numRows = grid1.length;
6+
int numCols = grid1[0].length;
7+
int subIslandCount = 0;
8+
boolean[][] visited = new boolean[numRows][numCols];
9+
for (int i = 0; i < numRows; i++) {
10+
for (int j = 0; j < numCols; j++) {
11+
if (!visited[i][j] && grid2[i][j] == 1) {
12+
Queue<int[]> queue = new LinkedList<>();
13+
queue.add(new int[]{i, j});
14+
boolean isSubisland = true;
15+
while (!queue.isEmpty()) {
16+
int[] removed = queue.remove();
17+
int x = removed[0];
18+
int y = removed[1];
19+
if (visited[x][y]) {
20+
continue;
21+
}
22+
if (grid1[x][y] != 1) {
23+
isSubisland = false;
24+
}
25+
visited[x][y] = true;
26+
for (int[] dir : DIRS) {
27+
int newX = x + dir[0];
28+
int newY = y + dir[1];
29+
if (newX >= 0 && newY >= 0 && newX < numRows && newY < numCols && !visited[newX][newY] && grid2[newX][newY] == 1) {
30+
queue.add(new int[]{newX, newY});
31+
}
32+
}
33+
}
34+
if (isSubisland) {
35+
subIslandCount++;
36+
}
37+
}
38+
}
39+
}
40+
return subIslandCount;
41+
}
42+
}

0 commit comments

Comments
 (0)