← Whiteboard questions

Longest Increasing Path in a Matrix

Find the longest uphill walk across a grid of heights

DSA, Hard, 2-D DP

Which structure or algorithm, and what does it cost.

A grid heights holds the height of each cell. A climb starts at any cell and moves one step up, down, left or right, onto a neighbour that is strictly higher than the current cell. A climb never leaves the grid. Return the number of cells in the longest climb. A single cell counts as a climb of 1.

Examples

Input heights = [[4, 8, 3], [6, 7, 9], [2, 5, 1]]
Output 4
Why start at 2, go to 6, then 7, then 9. Every step is strictly higher. No climb has five cells.
Input heights = [[5, 5], [5, 5]]
Output 1
Why all heights are equal, so no step goes strictly higher.
Input heights = [[1, 2, 3], [6, 5, 4], [7, 8, 9]]
Output 9
Why the climb goes 1, 2, 3, down to 4, left through 5 and 6, down to 7, then right to 8 and 9.

Constraints

Your answer must contain

Target Aim for O(R * C) time and O(R * C) memory, where R and C are the numbers of rows and columns.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

From one cell you can only step to a higher neighbour. Does the longest climb from a cell depend on how you got there?

Hint 2 the approach

It depends only on the cell. So each cell's answer can be found once and reused. Which cells must be known before a given cell?

Hint 3 the key step

Save each cell's answer the first time you find it: 1 plus the best answer among its strictly higher neighbours. Equal heights never count.

Walkthrough

Full walkthrough brute force to best

Brute force

From every cell, follow every possible climb with a depth-first search and keep the longest. The number of climbs can grow exponentially, for example on a grid whose heights rise toward one corner, so this is too slow for a 100 by 100 grid.

Better method

Memoised depth-first search. Let climb(r, c) be the longest climb that starts at (r, c): 1 plus the largest climb over its strictly higher neighbours. Store each result. Each cell is solved once and looks at 4 neighbours, so O(R * C) time and memory. The recursion can be R * C deep, for example on a spiral that climbs through every cell, and that overflows the stack in some languages.

Best method

Peel the grid in layers. Give every cell a count: how many of its four neighbours are strictly lower. A cell with count 0 has nothing below it, so a climb can start there. Those cells are layer 1. Remove them: for each removed cell, lower the count of each strictly higher neighbour by 1. A neighbour whose count reaches 0 has had every lower neighbour removed, so it joins the next layer. A cell lands in layer 1 + the largest layer among its lower neighbours, which is the length of the longest climb that ends there. So the number of layers is the longest climb. Equal heights never count each other, so a flat grid is one layer. Each cell is added once and looks at 4 neighbours, so there is no sort and no recursion.

Hand trace

Run on heights = [[4, 8, 3], [6, 7, 9], [2, 5, 1]]. The counts of lower neighbours are [[0, 3, 0], [2, 2, 3], [0, 2, 0]]. Layer 1 holds the heights 4, 3, 2, 1. Layer 2 holds the heights 6, 5. Layer 3 holds the heights 7. Layer 4 holds the heights 8, 9. There are 4 layers, so the answer is 4.

Code

def longest_climb(heights):
    rows, cols = len(heights), len(heights[0])
    steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
    lower = [[0] * cols for _ in range(rows)]      # lower[r][c]: strictly lower neighbours not yet peeled
    for r in range(rows):
        for c in range(cols):
            for dr, dc in steps:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and heights[nr][nc] < heights[r][c]:
                    lower[r][c] += 1
    layer = [(r, c) for r in range(rows) for c in range(cols) if lower[r][c] == 0]
    count = 0
    while layer:
        count += 1
        nxt = []
        for r, c in layer:
            for dr, dc in steps:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and heights[nr][nc] > heights[r][c]:
                    lower[nr][nc] -= 1
                    if lower[nr][nc] == 0:
                        nxt.append((nr, nc))
        layer = nxt
    return count

Time and memory

O(R * C) time: each cell is counted once, queued once and checks 4 neighbours. O(R * C) memory for the counts and the layers.

Common mistakes

  • Counting a neighbour of equal height as lower. In a flat grid like example 2 no cell then reaches a count of 0, and the answer is 0 instead of 1.
  • Returning the number of peeled cells instead of the number of layers. The answer counts the cells on one climb, one per layer.
  • Searching from every cell with no saved answers. The same cells are explored again and again, and the time grows exponentially.
  • Using >= instead of > in the memoised search. Two equal neighbours call each other forever, and example 2 never finishes.

Related problems

More 2-D DP problems
Longest Increasing Path in a Matrix walkthrough