Longest Increasing Path in a Matrix
LeetCode 329 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Strictly increasing edges form a DAG ⇒ memoised DFS.
ನಾನು Longest Increasing Path in a Matrix (LeetCode 329) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Graph DP ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
From any cell, you may step to a neighbour with a larger value. Because values must strictly increase there are no cycles, so the longest path from a cell is 1 + the longest path from its best larger neighbour — cache it and every cell is solved once.
Approach
- 1
dfs(r, c) = longest increasing path starting at (r, c).
- 2
Try the four directions; recurse only into in-bounds, strictly larger neighbours.
- 3
Store the result in memo.
- 4
Answer = max dfs over every cell.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
DFS + memo on a DAGPythonO(m·n) time · O(m·n) space
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m = len(matrix)
n = len(matrix[0])
memo = {}
def dfs(row,col):
key = (row,col)
if key in memo:
return memo[key]
di = [0,+1,0,-1]
dj = [+1,0,-1,0]
max_length = 1
for k in range(4):
nrow = row+di[k]
ncol = col+dj[k]
if 0<=nrow<m and 0<=ncol<n and matrix[nrow][ncol]>matrix[row][col]:
max_length=max(max_length,1+dfs(nrow,ncol))
memo[key]=max_length
return memo[key]
max_length = 0
for i in range(m):
for j in range(n):
max_length= max(dfs(i,j),max_length)
return max_length
Longest Increasing Path in a Matrix — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Longest Increasing Path in a Matrix ಹಿಂದಿನ intuition ಏನು?
From any cell, you may step to a neighbour with a larger value. Because values must strictly increase there are no cycles, so the longest path from a cell is 1 + the longest path from its best larger neighbour — cache it and every cell is solved once.
Longest Increasing Path in a Matrix (LeetCode 329) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. dfs(r, c) = longest increasing path starting at (r, c). 2. Try the four directions; recurse only into in-bounds, strictly larger neighbours. 3. Store the result in memo. 4. Answer = max dfs over every cell.
Longest Increasing Path in a Matrix ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(m · n). Space: O(m · n). (Accepted approach: DFS + memo on a DAG.)
Longest Increasing Path in a Matrix ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
No visited set is needed — strict increase already prevents cycles. Equal neighbours are not allowed.