Skip to main content

Longest Increasing Path in a Matrix

HardPremium

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

From each cell you can move up, down, left or right. You can't move diagonally or outside the grid, and each step must go to a strictly larger value.

Example 1

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

The longest increasing path is 1 → 2 → 6 → 9.

Example 2

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

The longest increasing path is 3 → 4 → 5 → 6. Moving diagonally isn't allowed.

Constraints

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