| 18 | } |
| 19 | |
| 20 | fun 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 | |
| 38 | fun isWithinBounds(r: Int, c: Int, matrix: List<List<Int>>): Boolean { |
| 39 | return r in matrix.indices && c in matrix[0].indices |
no test coverage detected