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

Method dfs

java/Graphs/CountIslands.java:20–34  ·  view source on GitHub ↗
(int r, int c, int[][] matrix)

Source from the content-addressed store, hash-verified

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;

Callers 1

countIslandsMethod · 0.95

Calls 1

isWithinBoundsMethod · 0.95

Tested by

no test coverage detected