longest-increasing-path-in-a-matrix.sh — zsh

Longest Increasing Path in a Matrix

hard
matrixgraphdynamic-programmingbreadth-first-search

Given an m x n integer matrix, you may start from any cell and move up, down, left, or right. You may only move to a cell with a strictly larger value. Return the length of the longest valid path.

Input / output

  • Input: matrix: int[][]
  • Output: length of the longest strictly increasing path

Examples

  1. matrix = [[9,9,4],[6,6,8],[2,1,1]] returns 4 from the path 1 -> 2 -> 6 -> 9.
  2. matrix = [[3,4,5],[3,2,6],[2,2,1]] returns 4 from the path 3 -> 4 -> 5 -> 6.
  3. matrix = [[1]] returns 1.

Constraints

  • 1 <= m, n <= 200
  • -2^31 <= matrix[r][c] <= 2^31 - 1

Target complexity

  • Aim for O(m * n) or O(m * n + edges) time, not exponential search.

Hints

  1. If you treat each cell as a graph node with directed edges to larger neighbors, the graph is acyclic.
  2. Local peaks have outdegree 0. Repeatedly peel one topological layer at a time, or memoize DFS results per cell.

Follow-up Why does allowing diagonal moves change only the neighbor count, not the core DAG reasoning?

Examples
Example 1
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Example 2
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Example 3
Input: matrix = [[1]]
Output: 1
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.