Skip to content

Commit 4ff70ba

Browse files
committed
Add important condition to avoid calculating nodes again
1 parent 8ef549f commit 4ff70ba

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

leetcode/hard/longest_increasing_path_in_a_matrix.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@ class Solution:
88
@staticmethod
99
def longestIncreasingPath(matrix: [[int]]) -> int:
1010
def dfs(row: int, col: int) -> int:
11-
val = matrix[row][col]
12-
dfs_up = dfs(row - 1, col) if row and val < matrix[row - 1][col] else 0
13-
dfs_down = dfs(row + 1, col) if row + 1 < m and val < matrix[row + 1][col] else 0
14-
dfs_left = dfs(row, col - 1) if col and val < matrix[row][col - 1] else 0
15-
dfs_right = dfs(row, col + 1) if col + 1 < n and val < matrix[row][col + 1] else 0
16-
dp[row][col] = 1 + max(dfs_up, dfs_down, dfs_left, dfs_right)
11+
if not dp[row][col]: # only calculate if not already done
12+
val = matrix[row][col]
13+
dfs_up = dfs(row - 1, col) if row and val < matrix[row - 1][col] else 0
14+
dfs_down = dfs(row + 1, col) if row + 1 < m and val < matrix[row + 1][col] else 0
15+
dfs_left = dfs(row, col - 1) if col and val < matrix[row][col - 1] else 0
16+
dfs_right = dfs(row, col + 1) if col + 1 < n and val < matrix[row][col + 1] else 0
17+
dp[row][col] = 1 + max(dfs_up, dfs_down, dfs_left, dfs_right)
1718
return dp[row][col]
1819

1920
m, n = len(matrix), len(matrix[0])

0 commit comments

Comments
 (0)