HardArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchGraphTopological SortMemoizationMatrix

Longest Increasing Path in a Matrix

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now