Show problems as
Classic problem #329HardArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchGraph TheoryTopological SortMemoizationMatrixDirected Acyclic Graph

Longest Increasing Path in a Matrix

Real-world version: Tallest Stack Ascent
Tracked in this browser only
Read Longest Increasing Path in a Matrix on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstDirected Acyclic Graph (DAG) Traversal · Graphs, animated step by step

A container yard is laid out as a rectangular grid of bays. heights[r][c] is how many containers are stacked in the bay at row r, column c.

A gantry inspector walks the yard bay by bay. From a bay the inspector may step to a bay sharing an edge with it, up, down, left or right, and only if that bay's stack is strictly taller than the one just left. Diagonal steps are not possible, and the walk may not leave the yard.

The inspector picks the starting bay. Return the greatest number of bays a single walk can cover, counting the starting bay itself.

Examples

Example 1

Input
heights = [[1, 5, 9], [2, 4, 8], [3, 7, 6]]
Output
5

Starting at the bay holding 1 the inspector can reach 2, then 4, then 5, then 9, covering five bays. No walk covers six.

Example 2

Input
heights = [[4, 4], [4, 4]]
Output
1

Every stack is the same height, so no step is ever allowed and the walk is the starting bay on its own.

Example 3

Input
heights = [[2, 3, 6], [5, 4, 7]]
Output
4

From 2 the inspector goes to 3, then down to 4, then left to 5, covering four bays. The route through 6 and 7 also stops at four.

Constraints

  • rows == heights.length
  • cols == heights[r].length
  • 1 <= rows, cols <= 200
  • 0 <= heights[r][c] <= 2^31 - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def longest_ascent(heights: list[list[int]]) -> int:
Java
public int longestAscent(int[][] heights)