Skip to content

Commit f08e78f

Browse files
committed
add: CountIslands
1 parent 4e2b2a7 commit f08e78f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

java/Graphs/CountIslands.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
public class CountIslands {
2+
public int countIslands(int[][] matrix) {
3+
if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
4+
return 0;
5+
}
6+
int count = 0;
7+
for (int r = 0; r < matrix.length; r++) {
8+
for (int c = 0; c < matrix[0].length; c++) {
9+
// If a land cell is found, perform DFS to explore the full
10+
// island, and include this island in our count.
11+
if (matrix[r][c] == 1) {
12+
dfs(r, c, matrix);
13+
count++;
14+
}
15+
}
16+
}
17+
return count;
18+
}
19+
20+
private void dfs(int r, int c, int[][] matrix) {
21+
// Mark the current land cell as visited.
22+
matrix[r][c] = -1;
23+
// Define direction vectors for up, down, left, and right.
24+
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
25+
// Recursively call DFS on each neighboring land cell to continue
26+
// exploring this island.
27+
for (int[] d : dirs) {
28+
int nextR = r + d[0];
29+
int nextC = c + d[1];
30+
if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) {
31+
dfs(nextR, nextC, matrix);
32+
}
33+
}
34+
}
35+
36+
private boolean isWithinBounds(int r, int c, int[][] matrix) {
37+
return 0 <= r && r < matrix.length && 0 <= c && c < matrix[0].length;
38+
}
39+
}

0 commit comments

Comments
 (0)