Menu
CoddyTech

Longest Increasing Path in a Matrix

You get matrix, a grid of whole numbers with m rows and n columns, as a list of rows. A path steps up, down, left or right (no diagonals, no wrapping around the edges), and every step must land on a strictly larger value. Return the number of cells on the longest such path. A single cell is a path of 1 cell.

Function

longestIncreasingPath(matrix: integer-2d-array) → integer
matrixinteger-2d-array
the grid of values, as a list of rows of equal length
Returnsinteger
the number of cells on the longest strictly increasing path

Constraints

  • 1 ≤ m, n ≤ 100, where m = matrix.length and n = matrix[i].length
  • Every row has the same length n.
  • 0 ≤ matrix[i][j] ≤ 231-1

Examples

Input
matrix = [[9, 8, 3], [2, 7, 4], [1, 6, 5]]
Output
7
Explanation
The path 3, 4, 5, 6, 7, 8, 9 runs down the right column, along the bottom row and up the middle column to the 9: 7 cells. From the smallest value, 1, the best paths have 5 cells.
challenge icon

Follow-up

Can you also return the cells of one longest path, along with its length?

Reset code
def longestIncreasingPath(matrix):
    # Write code here

Test #1

Test #2

Test #3

Argument

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

Expected Output

7