Longest Increasing Path in a Matrix

Hard · 2-D Dynamic Programming · Array · Dynamic Programming · Depth-First Search · Breadth-First Search · Graph · Topological Sort · Memoization · Matrix

Problem

Given an m × n grid of integers, return the length of the longest strictly increasing path in it.

From a cell you may step up, down, left or right, but not diagonally and not off the edge. Every step must go to a strictly larger value, so two equal neighbours never form a step. The length counts cells: a single cell is a path of length 1.

Some tests contain increasing paths thousands of cells long, which is deeper than Python’s default recursion limit of 1,000. A recursive search has to be made iterative to pass them.

Examples

Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4

The path 1, 2, 6, 9 starts at the bottom middle, steps left, then up twice.

Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4

The path 3, 4, 5, 6 runs along the top row and turns down. Moving diagonally is not allowed.

Constraints

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…