Tallest Staircase Walk Across a Number Board
Dynamic ProgrammingAuto-graded · 21 test casesLast updated
Find the longest chain of orthogonally adjacent cells with strictly increasing values in a 2D grid, testing DAG longest-path DP, memoization, and avoiding deep recursion.
Tallest Staircase Walk Across a Number Board
You are given a rectangular board of integers, stored as a list of rows. A staircase walk starts on any cell and repeatedly moves to one of the four orthogonally adjacent cells (up, down, left, right). Every move must land on a cell whose value is strictly greater than the value of the cell you are leaving. Moves cannot leave the board, and diagonal moves are not allowed.
The length of a walk is the number of cells it visits, including the starting cell. A walk consisting of a single cell has length 1.
Return the length of the longest staircase walk that exists anywhere on the board.
Rules and edge cases
- If the board has no rows, or its first row is empty, return
0. - Equal values never form a step, because the comparison must be strictly greater.
- Values may be negative or repeated.
- The board may be large, and a valid walk can pass through a very large number of cells, so be careful with recursion depth in your language.
Constraints
- The board has
mrows andncolumns, with0 <= m, n; all rows have the same length. - Each value is an integer that fits in a standard 32-bit signed integer.
- Aim for a solution that runs in
O(m * n)time (anO(m * n * log(m * n))approach is also acceptable for small boards). - The function receives the board and returns a single integer.
Examples
Example 1
Input: longest_staircase_walk([[9, 9, 4], [6, 6, 8], [2, 1, 1]])
Output: 4
Example 2
Input: longest_staircase_walk([[3, 4, 5], [3, 2, 6], [2, 2, 1]])
Output: 4
Example 3
Input: longest_staircase_walk([[1]])
Output: 1
Hints
Hint 1
Draw an arrow from each cell to every neighbor with a strictly larger value. Can this graph contain a cycle? What does that imply about how to compute longest paths?
Hint 2
Let best[cell] be the longest walk that starts at that cell. It equals 1 plus the maximum best[] among strictly larger neighbors (or just 1 if there are none). Cache each result so every cell is computed once.
Hint 3
Deep recursion can be a problem on huge boards. Consider an explicit stack, processing cells in descending value order, or peeling off layers of cells with no larger neighbor (Kahn-style) and counting the layers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each cell as a node and draw a directed edge from a cell to each adjacent cell with a strictly larger value. Values strictly increase along every edge, so a cycle is impossible: the graph is a directed acyclic graph (DAG). The task becomes finding the longest path in a DAG.
Define dp[cell] as the length of the longest staircase walk that starts at that cell:
dp[cell] = 1 + max(dp[nb] for each strictly larger neighbor nb), or 1 if there is none
The answer is the maximum dp over all cells (or 0 for an empty board).
Plain DFS from every cell without caching repeats work and can be exponential. Memoizing means each cell is computed exactly once.
Avoiding deep recursion
A walk can cover up to m * n cells (for example a snake of increasing values), which would overflow Python's recursion limit. The reference solution therefore runs the DFS with an explicit stack. Each frame holds [row, col, next_direction], so it can resume where it left off, like a returning recursive call.
Each cell has a state: 0 unseen, 1 on the stack, 2 finished. The loop:
- Look at the top frame. If directions remain, advance the counter and examine that neighbor. If it is in bounds, strictly larger, and unseen, mark it active and push it.
- When all four directions have been examined, every strictly larger neighbor is finished. Compute
dpfrom them, mark the cell finished, update the best answer, and pop.
Why it is correct
- Cells on the stack have strictly increasing values from bottom to top, so a strictly larger neighbor of the top cell can never be an active cell. It is either finished or unseen (and then gets pushed and finished before the top frame completes).
- Hence every
dpvalue is computed only after all of its dependencies are final, which is the reverse topological order that DFS finishing order provides. - The outer loops start a DFS from every unseen cell, so every cell is covered.
Complexity
- Time:
O(m * n). Each cell is pushed and popped once, with constant work (up to 8 neighbor checks) per cell. - Space:
O(m * n)fordp,state, and the explicit stack in the worst case.
Alternatives
- Kahn-style peeling: count each cell's number of strictly larger neighbors, start from cells with count 0, and remove layers; the number of layers is the answer. Also
O(m * n). - Sort cells by value in descending order and fill
dpin that order:O(m * n * log(m * n)).
Reference solution
from typing import List
def longest_staircase_walk(board: List[List[int]]) -> int:
if not board or not board[0]:
return 0
m, n = len(board), len(board[0])
dp = [[0] * n for _ in range(m)]
state = [[0] * n for _ in range(m)] # 0 = unseen, 1 = active, 2 = finished
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
best = 0
for sr in range(m):
for sc in range(n):
if state[sr][sc] != 0:
continue
state[sr][sc] = 1
stack = [[sr, sc, 0]]
while stack:
r, c, next_direction = stack[-1]
if next_direction < 4:
stack[-1][2] += 1
dr, dc = directions[next_direction]
nr, nc = r + dr, c + dc
if (
0 <= nr < m
and 0 <= nc < n
and board[nr][nc] > board[r][c]
and state[nr][nc] == 0
):
state[nr][nc] = 1
stack.append([nr, nc, 0])
continue
longest = 1
value = board[r][c]
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (
0 <= nr < m
and 0 <= nc < n
and board[nr][nc] > value
):
longest = max(longest, 1 + dp[nr][nc])
dp[r][c] = longest
state[r][c] = 2
best = max(best, longest)
stack.pop()
return best