MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / CountIslands

Class CountIslands

java/Graphs/CountIslands.java:1–39  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1public 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected