687. Longest Climbing Path

A hiking club maps a rectangular region as a grid where grid[r][c] is the altitude of cell (r, c). A hiker can move from a cell to any of its four side-adjacent neighbours, but only if that neighbour is strictly higher. The hiker may start anywhere and stop anywhere.

Return the largest number of cells on any climbing route, counting the starting cell. Because altitude must keep rising, a route never visits a cell twice. Equal altitudes block movement, so a grid where every cell has the same altitude gives 1.

A route can snake through every cell of a large grid, so avoid unbounded recursion and avoid re-exploring cells; the intended solution runs in O(rows * cols) time.

Example 1

Input:
grid = [[3,4,5],[2,2,6],[1,9,8]]
Output:
8
Explanation:

The route 1, 2, 3, 4, 5, 6, 8, 9 climbs strictly at every step and visits 8 cells.

Example 2

Input:
grid = [[7,7],[7,7]]
Output:
1
Explanation:

Equal altitudes block every move, so the best route is a single cell.

Constraints

1 ≤ rows, cols ≤ 300

0 ≤ grid[r][c] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(rows * cols)
Space
O(rows * cols)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…