CodeArchon

hard2-D Dynamic ProgrammingGoogleFacebook

Hillside Climber

A hiker finds the longest strictly ascending trail on an elevation grid moving one cell at a time (4-way).

Given an m×n matrix of integers, return the length of the longest strictly increasing path moving up/down/left/right.

Choose approach

9
cur
9
4
6
6
8
2
1
1
1/10
Narrationstep 1 of 10

Memoized longest from (0,0) = 1. Global best = 1.

1def longestIncreasingPath(matrix):
2 m, n = len(matrix), len(matrix[0])
3 memo = [[0]*n for _ in range(m)]
4 def dfs(r, c):
5 if memo[r][c]: return memo[r][c]
6 best = 1
7 for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
8 nr, nc = r+dr, c+dc
9 if 0 <= nr < m and 0 <= nc < n and matrix[nr][nc] > matrix[r][c]:
10 best = max(best, 1 + dfs(nr, nc))
11 memo[r][c] = best
12 return best
13 return max(dfs(r, c) for r in range(m) for c in range(n))
Variables
r=0
c=0
local=1
best=1

How to think about it

  1. Strictly increasing -> no cycles -> clean memoization.
  2. Each cell computed exactly once.

Edge cases to catch in interview

  • All equal -> 1.
  • Single cell -> 1.

Examples

Example 14
{"matrix":[[3,4,5],[3,2,6],[2,2,1]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed