Skip to problem
←

Longest Increasing Path in a Matrix

Hard 0 attempts

Given an m x n matrix of integers, find the longest path you can trace where each step strictly increases in value. From any cell you may only step up, down, left, or right (no diagonal moves, and never off the edge of the grid), and every move must land on a cell whose value is strictly larger than the one you're leaving.

Return the number of cells in the path, including both endpoints.

You may start and end at any cell. Equal values cannot extend a path, and the grid does not wrap at its edges. A matrix whose values are all equal has answer 1.

Function contract

Implement longestIncreasingPathInAMatrix(matrix). Receive a nonempty rectangular matrix of integers.

Output: Return the maximum number of cells in any strictly increasing path, including its starting cell.

Example 1

Input
matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output
4

Example 2

Input
matrix = [[1]]
Output
1
Visual Aid
Count cells, not moves
An increasing path of four cellsIn the matrix 9 9 4; 6 6 8; 2 1 1, start at the bottom middle 1, move left to 2, then up to 6 and up to 9.9946682111 → 2 → 6 → 94 cells · 3 movesReturn 4Every step moves to a larger adjacent value.

One longest path starts at row 2, column 1 (zero-based), moves left, then up twice. All moves are horizontal or vertical.

Constraints
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1

Topological Layers

Orient edges from smaller cells to larger neighbors. Cells with no smaller neighbor start the first layer. Remove them, decrement successor indegrees, and repeat. The number of layers equals the longest increasing path; strict increases make the graph acyclic.

javascript
function longestIncreasingPathInAMatrix(matrix) {
  const rows = matrix.length,
    cols = matrix[0].length,
    dirs = [
      [1, 0],
      [-1, 0],
      [0, 1],
      [0, -1],
    ];
  const indegree = Array.from({ length: rows }, () => Array(cols).fill(0)),
    queue = [];
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; c++) {
      for (const [dr, dc] of dirs) {
        const nr = r + dr,
          nc = c + dc;
        if (
          nr >= 0 &&
          nr < rows &&
          nc >= 0 &&
          nc < cols &&
          matrix[nr][nc] < matrix[r][c]
        )
          indegree[r][c]++;
      }
      if (indegree[r][c] === 0) queue.push([r, c]);
    }
  let head = 0,
    length = 0;
  while (head < queue.length) {
    const end = queue.length;
    length++;
    while (head < end) {
      const [r, c] = queue[head++];
      for (const [dr, dc] of dirs) {
        const nr = r + dr,
          nc = c + dc;
        if (
          nr >= 0 &&
          nr < rows &&
          nc >= 0 &&
          nc < cols &&
          matrix[nr][nc] > matrix[r][c] &&
          --indegree[nr][nc] === 0
        )
          queue.push([nr, nc]);
      }
    }
  }
  return length;
}

Time: O(rows × cols) | Space: O(rows × cols)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript