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 moves from cell to cell, one step up, down, left or right at a time (no diagonal steps, 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 on its own 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, left along the bottom row, up the middle column and left to the 9 in the corner: 7 cells. The smallest value does worse: from the 1 the best paths are 1, 2, 7, 8, 9 and 1, 6, 7, 8, 9, with 5 cells each.

lock icon+18 hidden tests on Submit

challenge icon

Follow-up

Can you also return the cells of one longest path, not only its length?

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

Case 1

Case 2

Case 3

Input

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

Expected

7