Maps app~30 min2s · 256 MBtarget O(R × C × log(R × C)) time, O(R × C) spaceclassic twin: lc-329dp
A hiking app stores a hill map as a grid of elevation readings. Each cell is a square patch of ground with one reading, in whole units. A walker moves from a cell to the cell above, below, left or right, never diagonally.
The app wants to suggest a climb: a walk where every step goes to a strictly higher reading. The walk can start in any cell. Your team lead asks: how many cells does the longest climb cover?
Write longest_rising_walk(heights).
heights is a grid with at least one row and one column. heights[r][c] is the reading of the cell in row r and column c.Input: heights = [[1, 5, 9], [2, 6, 8], [3, 4, 7]]
Output: 7Look at the cells from the lowest reading to the highest. A walk ending in a cell is one cell longer than the best walk ending in a lower neighbour. Let best be the length of the longest walk that ends in a cell. A cell is written as its row and column, counted from 0.
| Reading | Cell | Lower neighbours (their best) |
best |
|---|---|---|---|
| 1 | (0, 0) | none | 1 |
| 2 | (1, 0) | 1 (1) | 2 |
| 3 | (2, 0) | 2 (2) | 3 |
| 4 | (2, 1) | 3 (3) | 4 |
| 5 | (0, 1) | 1 (1) | 2 |
| 6 | (1, 1) | 2 (2), 4 (4), 5 (2) | 5 |
| 7 | (2, 2) | 4 (4) | 5 |
| 8 | (1, 2) | 6 (5), 7 (5) | 6 |
| 9 | (0, 2) | 5 (2), 8 (6) | 7 |
The longest walk ends at the reading 9 with 7 cells: 1, 2, 3, 4, 6, 8, 9.
Input: heights = [[4, 4], [4, 4]]
Output: 1Every reading is the same, so no step goes strictly higher. Each walk is a single cell.
Input: heights = [[3, 2, 1], [6, 5, 4]]
Output: 4The longest climb starts at the reading 1 in the top right, and goes down to 4, then left to 5 and left to 6. It covers 4 cells.
1 ≤ rows ≤ 300 and 1 ≤ columns ≤ 300, and every row has the same length0 ≤ heights[r][c] ≤ 1000000A grid of 300 × 300 has 90,000 cells. A search that follows every climbing step from every cell, with no memory, can repeat the same part of a walk millions of times. On a smooth slope the number of walks has more than 100 digits.
A walk can also be 90,000 cells long, so a recursive search needs 90,000 nested calls. Handle each cell once, in an order where every lower neighbour is already done.