HardPro challengePythonJavaScriptTypeScript
DP — Longest Increasing Path in a Matrix
AlgorithmsDynamic ProgrammingGraphsMemoization
solve(matrix) — from any cell you can move up, down, left or right (no diagonals,
no wrapping) to a neighbour with a strictly larger value. Return the length, in
cells, of the longest such path.
The "is larger" relation makes the grid a DAG, so the longest path starting from a
cell never revisits a cell. Run a DFS from every cell and memoize the result per
cell: each cell is computed once, giving O(rows × cols).
Examples
solve([[9,9,4],[6,6,8],[2,1,1]]) → 4 // 1 → 2 → 6 → 9
solve([[3,4,5],[3,2,6],[2,2,1]]) → 4 // 3 → 4 → 5 → 6
solve([[1]]) → 1
solve([[1,2,3],[6,5,4],[7,8,9]]) → 9Sample tests
Test #1Classic example
Input: [[[9,9,4],[6,6,8],[2,1,1]]]
Output: 4
Test #2Second classic example
Input: [[[3,4,5],[3,2,6],[2,2,1]]]
Output: 4
Test #3Single cell
Input: [[[1]]]
Output: 1