HardArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchGraphTopological SortMemoizationMatrix

1 approach, code in every language

Problem description

You are given an m x n grid of integers. Starting from any cell you may repeatedly move to one of the four horizontally or vertically adjacent cells, but only when the value of the destination cell is strictly greater than the value of the current cell.

A path is the sequence of cells visited by such moves, and its length is the number of cells it contains. You may begin and end at any cells you like, and diagonal moves or wrapping around the borders are not permitted.

Return the length of the longest strictly increasing path that can be formed in the grid.

Example 1

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

Output: 4

The longest increasing path is 1 -> 2 -> 6 -> 9, which visits four cells.

Example 2

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

Output: 4

The path 3 -> 4 -> 5 -> 6 is the longest; equal values cannot be chained because moves must be strictly increasing.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1

After the pattern

Now solve one you haven't seen.

Tallest Stack Ascent is our own problem on the technique behind Longest Increasing Path in a Matrix: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free