329. Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]

Return 4 The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]

Return 4 The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Solution: DFS

UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)


class Solution(object):
    def longestIncreasingPath(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: int
        """
        if not matrix:
            return 0

        rows = len(matrix)
        cols = len(matrix[0])
        memo = [[0] * cols for _ in xrange(rows)]

        def neighbors(row, col):
            for x, y in UP, DOWN, LEFT, RIGHT:
                i = row + x
                j = col + y
                if 0 <= i < rows and 0 <= j < cols:
                    yield i, j

        def dfs(row, col):
            if memo[row][col]:
                return memo[row][col]
            max_path = 1
            for i, j in neighbors(row, col):
                if matrix[i][j] > matrix[row][col]:
                    max_path = max(max_path, dfs(i, j) + 1)
            memo[row][col] = max_path
            return max_path

        max_path = 0
        for i in xrange(rows):
            for j in xrange(cols):
                max_path = max(max_path, dfs(i, j))
        return max_path

Lessons:

  • For each cell, use DFS to find its longest path.
  • During DFS, cache all calculated (visited) cells.

results matching ""

    No results matching ""