Skip to content

Commit a2c764a

Browse files
committed
Create 0329-longest-increasing-path-in-a-matrix.swift
1 parent 3418fa8 commit a2c764a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
func longestIncreasingPath(_ matrix: [[Int]]) -> Int {
3+
let rows = matrix.count, cols = matrix[0].count
4+
var dp = [[Int]: Int]()
5+
6+
func dfs(_ r: Int, _ c: Int, _ prev: Int) -> Int {
7+
if r < 0 || r == rows || c < 0 || c == cols || matrix[r][c] <= prev {
8+
return 0
9+
}
10+
if dp[[r, c]] != nil {
11+
return dp[[r, c]]!
12+
}
13+
var res = 1
14+
res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))
15+
res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))
16+
res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))
17+
res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))
18+
dp[[r, c]] = res
19+
return res
20+
}
21+
22+
for r in 0..<rows {
23+
for c in 0..<cols {
24+
dfs(r, c, -1)
25+
}
26+
}
27+
28+
return dp.values.max()!
29+
}
30+
}

0 commit comments

Comments
 (0)