【LeetCode】329. Longest Increasing Path in a Matrix 解題報告(Python)
阿新 • • 發佈:2018-12-12
題目描述:
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:
Input: nums = [ [9,9,4], [6,6,8], [2,1,1] ] Output: 4 Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
題目大意
求二維矩陣中最長的遞增路徑。
解題方法
和417. Pacific Atlantic Water Flow非常類似,直接DFS求解。一般來說DFS需要有固定的起點,但是對於這個題,二維矩陣中的每個位置都算作起點。
把每個位置都當做起點,然後去做個dfs,看最長路徑是多少。然後再找出全域性的最長路徑。使用cache儲存已經訪問過的位置,這樣能節省了很多搜尋的過程,然後有個continue是為了剪枝。因為這個做法比較暴力,就沒有什麼好講的了。
最壞情況下的時間複雜度是O((MN)^2),空間複雜度是O(MN)。
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
res = 0
cache = [[-1] * n for _ in range(m)]
for i in range(m):
for j in range(n):
path = self.dfs(matrix, cache, m, n, i, j)
res = max(res, path)
return res
def dfs(self, matrix, cache, m, n, i, j):
if cache[i][j] != -1:
return cache[i][j]
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
res = 1
for dire in directions:
x, y = i + dire[0], j + dire[1]
if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] <= matrix[i][j]:
continue
path = 1 + self.dfs(matrix, cache, m, n, x, y)
res = max(path, res)
cache[i][j] = res
return cache[i][j]
參考資料:
日期
2018 年 10 月 1 日 —— 歡度國慶!