KatInterview

Climbing the Tallest Staircase Through a Height Map

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingdynamic-programminggridtopological-order

Last 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) <= 200
  • 1 <= len(grid[i]) <= 200, and every row has the same length
  • 0 <= 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.