Longest Increasing Path in a Matrix

Hard Advanced graphs AI round

matrix is a grid of whole numbers with m rows and n columns.

From a cell you may step to a neighbouring cell: the one above, below, left or right of it, never diagonally and never past the edge of the grid. A path is increasing when every step goes to a cell that holds a larger number than the cell before it. A single cell is an increasing path too.

Return the number of cells in the longest increasing path in matrix.

Example 1

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

The path 2, 4, 5, 6, 7, 8 starts in the middle, steps down to 4, goes round the left side and up to 8 at the top: six cells, each larger than the one before. 8 has no larger neighbour and 2 no smaller one, so the path can grow at neither end.

Example 2

Input: matrix = [[-5,0,3,3,8]]
Output: 3

Example 3

Input: matrix = [[4,4,4],[4,4,4]]
Output: 1

Constraints

  • 1 ≤ m, n ≤ 200
  • Every row of matrix has n numbers
  • -10⁹ ≤ matrix[i][j] ≤ 10⁹

More Advanced graphs

All Advanced graphs problems