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

Function dfs

kotlin/Graphs/CountIslands.kt:19–33  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17}
18
19fun dfs(r: Int, c: Int, matrix: MutableList<MutableList<Int>>) {
20 // Mark the current land cell as visited.
21 matrix[r][c] = -1
22 // Define direction vectors for up, down, left, and right.
23 val dirs = listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))
24 // Recursively call DFS on each neighboring land cell to continue
25 // exploring this island.
26 for (d in dirs) {
27 val nextR = r + d.first
28 val nextC = c + d.second
29 if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] == 1) {
30 dfs(nextR, nextC, matrix)
31 }
32 }
33}
34
35fun isWithinBounds(r: Int, c: Int, matrix: MutableList<MutableList<Int>>): Boolean {
36 return r in matrix.indices && c in matrix[0].indices

Callers 1

countIslandsFunction · 0.70

Calls 2

isWithinBoundsFunction · 0.70
PairClass · 0.50

Tested by

no test coverage detected