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

Function dfs

kotlin/Graphs/LongestIncreasingPath.kt:20–36  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

18}
19
20fun dfs(r: Int, c: Int, matrix: List<List<Int>>, memo: Array<IntArray>): Int {
21 if (memo[r][c] != 0) {
22 return memo[r][c]
23 }
24 var maxPath = 1
25 val dirs = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)
26 // The longest path starting at the current cell is equal to the
27 // longest path of its larger neighboring cells, plus 1.
28 for (d in dirs) {
29 val (nextR, nextC) = r + d.first to c + d.second
30 if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] > matrix[r][c]) {
31 maxPath = maxOf(maxPath, 1 + dfs(nextR, nextC, matrix, memo))
32 }
33 }
34 memo[r][c] = maxPath
35 return maxPath
36}
37
38fun isWithinBounds(r: Int, c: Int, matrix: List<List<Int>>): Boolean {
39 return r in matrix.indices && c in matrix[0].indices

Callers 1

longestIncreasingPathFunction · 0.70

Calls 1

isWithinBoundsFunction · 0.70

Tested by

no test coverage detected