CodingNodes / 2-D Dynamic Programming / Longest Increasing Path In a Matrix System design Space play · ←→ step · R restart

Problem

You are given a grid of integers. A path starts at any cell and, at each step, moves one cell up, down, left or right (no diagonals, and it cannot leave the grid). Every step must land on a strictly bigger number than the cell it left.

Return the number of cells on the longest such path.

Constraints

  • 1 ≤ rows, cols ≤ 200
  • 0 ≤ matrix[i][j] ≤ 2³¹ − 1

Examples: pick one to animate

Solutions

TimeO(m · n) SpaceO(m · n)

Time: Every cell is solved exactly once, and each time it looks at the top of the stack it checks only its four neighbours.

Space: The memo has one number per cell, and the stack never holds more cells than the grid has.

Moves only go to strictly bigger numbers, so a path can never come back to a cell: the cells form a graph without cycles. The longest path that starts at a cell is 1 plus the best of the same answers for its bigger neighbours. Store each answer in a memo so it is computed only once. To solve a cell, first solve any bigger neighbour that has no answer yet (push it on a stack), and only when all of them are solved, combine them. An explicit stack replaces recursion, because a path can be 40,000 cells long on a 200 by 200 grid, which would overflow the call stack.