LeetCode 329. Longest Increasing Path in a Matrix
Description
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.
描述
給定一個整數矩陣,找出最長遞增路徑的長度。
對於每個單元格,你可以往上,下,左,右四個方向移動。 你不能在對角線方向上移動或移動到邊界外(即不允許環繞)。
示例 1:
輸入: nums = [ [9,9,4], [6,6,8], [2,1,1] ] 輸出: 4 解釋: 最長遞增路徑為 [1, 2, 6, 9]。
示例 2:
輸入: nums = [ [3,4,5], [3,2,6], [2,2,1] ] 輸出: 4 解釋: 最長遞增路徑是 [3, 4, 5, 6]。注意不允許在對角線方向上移動。
思路
- 這道題主要使用記憶化遞迴和深度優先遍歷。
- 我們以給定的矩陣的每一個位置為起點,進行深度優先遍歷。
- 我們儲存每個位置深度優先遍歷的結果,當下一次走到這個位置的時候,我們直接返回當前位置記錄的值,這樣可以減少遍歷的次數,加快執行速度。
- 二維矩陣 dp 初始化每個位置都為 0 ,當遍歷到某個位置不為 0 的時候,說明該位置已經遍歷過了,我們直接返回其值。
# -*- coding: utf-8 -*- # @Author:何睿 # @Create Date:2019-03-07 21:19:51 # @Last Modified by:何睿 # @Last Modified time: 2019-03-07 22:23:10 from itertools import product class Solution: def longestIncreasingPath(self, matrix: [[int]]) -> int: # 如果矩陣為空,返回 0 if not matrix or not matrix[0]: return 0 # 獲取矩陣的行數和列數 row, col = len(matrix), len(matrix[0]) # 記憶化遞迴,記錄每個位置的最大值 dp = [[0] * col for _ in range(row)] # 遍歷每一個位置,以每一個位置為起點進行深度優先遍歷 # 返回最大值 return max( self._dfs(i, j, row, col, matrix, dp) for i, j in product(range(row), range(col))) def _dfs(self, i, j, row, col, matrix, dp): # 如果當前位置不為零,說明當前位置的最大值已經被找到 # 採用記憶化遞迴,直接返回最大值 if dp[i][j]: return dp[i][j] # 遍歷四個方向 for x, y in [(0, -1), (-1, 0), (0, 1), (1, 0)]: m, n = x + i, y + j # 如果下一個位置沒有越界並且下一個位置的只嚴格大於位置i,j if 0 <= m < row and 0 <= n < col and matrix[i][j] < matrix[m][n]: # 記錄最大值 dp[i][j] = max(dp[i][j], self._dfs(m, n, row, col, matrix, dp)) # 把當前位置本身加上 dp[i][j] += 1 # 返回以當前位置為起點,所有路徑中的最大值 return dp[i][j]
原始碼檔案在這裡 。
©本文首發於何睿的部落格 ,歡迎轉載,轉載需保留文章來源 ,作者資訊和本宣告.
微信公眾號:techruicore