Climbing the Tallest Staircase Through a Height Map
Dynamic ProgrammingAuto-graded · 24 test casesLast updated
Find the longest chain of strictly rising values in a grid using only up, down, left, right steps, which tests DP over an implicit DAG with a valid processing order.
You are given a rectangular grid of integers, where each number represents the height of a tile. You want to walk across the grid, always stepping onto a strictly taller tile, and make the walk as long as possible.
Return the number of tiles on the longest such walk.
Movement rules
- A step goes from a tile to one of its four orthogonal neighbors (up, down, left or right).
- The tile you step onto must have a strictly greater value than the tile you leave. Equal values can never follow each other.
- Diagonal steps are not allowed.
- There is no wrap-around. The last column is not next to the first column, and the last row is not next to the first row.
- You may start on any tile. A single tile counts as a walk of length 1, so the answer is always at least 1.
- Return only the length, counted in tiles, and not the walk itself.
Constraints
1 <= len(grid) <= 2001 <= len(grid[i]) <= 200, and every row has the same length0 <= grid[i][j] <= 2^31 - 1
Examples
Example 1
Input: longest_rising_walk([[1, 2, 3], [6, 5, 4], [7, 8, 9]])
Output: 9
Example 2
Input: longest_rising_walk([[1, 0], [0, 2]])
Output: 2
Example 3
Input: longest_rising_walk([[4, 1, 2, 3]])
Output: 3
Hints
Hint 1
Define the state as the length of the longest rising walk that starts at a given tile. How does it relate to the same quantity for strictly taller neighbors?
Hint 2
Steps only go to strictly larger values, so no cycles exist. If you handle tiles from the largest value to the smallest, every neighbor you depend on is already computed.
Hint 3
If you flatten the grid into one index, check row and column bounds explicitly so that left and right moves do not wrap to an adjacent row. Also beware that a recursive version can go 40,000 levels deep.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let best[cell] be the length of the longest strictly increasing walk that starts at cell. A walk either stops immediately (length 1) or steps to a strictly larger orthogonal neighbor and continues from there:
best[cell] = 1 + max(best[n] for each neighbor n with value[n] > value[cell]), or 1 if none
Every dependency points to a strictly larger value, so if we process cells from the largest value to the smallest, all the neighbors a cell needs are already finished. This is a topological order of an implicit DAG, so one iterative pass fills the table.
To make this easy, the grid is flattened so that cell (r, c) has index r * C + c. The neighbors are idx - C, idx + C, idx - 1 and idx + 1, each guarded by explicit row or column bounds. The column guards matter: without them, idx - 1 in column 0 would land on the last cell of the previous row, which is the forbidden wrap-around.
Why it is correct
- Edges go only from smaller to strictly larger values, so there are no cycles and no tile is revisited.
- When a cell is processed, every strictly larger neighbor appears earlier in the descending order, so its value is final.
- Equal-valued neighbors are excluded by the strict
>check, so the arbitrary order among ties never matters. An unprocessed neighbor is never read. - The recurrence covers every case: a longest walk from a cell is either length 1 or a first step to a larger neighbor followed by a longest walk from that neighbor.
- The answer is the maximum over all cells, since a walk can start anywhere. It begins at 1 because a single tile is always valid.
An iterative order also avoids Python's recursion limit. A memoized DFS can recurse as deeply as the path length, up to 40,000 on a snake-like grid.
Complexity
With N = R * C:
- Time:
O(N log N)for the sort, plusO(N)for the DP pass (4 neighbor checks per cell). - Space:
O(N).
Reference solution
from typing import List
def longest_rising_walk(grid: List[List[int]]) -> int:
R, C = len(grid), len(grid[0])
flat = [v for row in grid for v in row]
order = sorted(range(R * C), key=flat.__getitem__, reverse=True)
best = [1] * (R * C)
ans = 1
for idx in order:
v = flat[idx]
r, c = divmod(idx, C)
b = 1
if r > 0 and flat[idx - C] > v and best[idx - C] + 1 > b:
b = best[idx - C] + 1
if r < R - 1 and flat[idx + C] > v and best[idx + C] + 1 > b:
b = best[idx + C] + 1
if c > 0 and flat[idx - 1] > v and best[idx - 1] + 1 > b:
b = best[idx - 1] + 1
if c < C - 1 and flat[idx + 1] > v and best[idx + 1] + 1 > b:
b = best[idx + 1] + 1
best[idx] = b
if b > ans:
ans = b
return ans