Skip to content

Commit df6e9b0

Browse files
authored
Merge pull request neetcode-gh#2701 from kousukekikuchi1984/feature/longest-increasing-path-in-a-matrix
Create 0329-longest-increasing-path-in-a-matrix.rs
2 parents 331d2a5 + 3b96efd commit df6e9b0

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
impl Solution {
2+
pub fn longest_increasing_path(matrix: Vec<Vec<i32>>) -> i32 {
3+
use std::cmp::max;
4+
use std::collections::HashMap;
5+
6+
let mut dp: HashMap::<(usize, usize), i32> = HashMap::new();
7+
8+
fn dfs(
9+
r: usize,
10+
c: usize,
11+
prevVal: i32,
12+
matrix: &[Vec<i32>],
13+
dp: &mut HashMap<(usize, usize), i32>,
14+
) -> i32 {
15+
if r < 0
16+
|| r >= matrix.len()
17+
|| c < 0
18+
|| c >= matrix[0].len()
19+
|| matrix[r][c] <= prevVal
20+
{
21+
return 0;
22+
}
23+
if let Some(&result) = dp.get(&(r, c)) {
24+
return result;
25+
}
26+
27+
let mut res = 1;
28+
res = max(res, 1 + dfs(r + 1, c, matrix[r][c], matrix, dp));
29+
res = max(res, 1 + dfs(r - 1, c, matrix[r][c], matrix, dp));
30+
res = max(res, 1 + dfs(r, c + 1, matrix[r][c], matrix, dp));
31+
res = max(res, 1 + dfs(r, c - 1, matrix[r][c], matrix, dp));
32+
dp.insert((r, c), res);
33+
res
34+
}
35+
36+
for r in 0..matrix.len() {
37+
for c in 0..matrix[0].len() {
38+
dfs(r, c, -1, &matrix, &mut dp);
39+
}
40+
}
41+
*dp.values().max().unwrap_or(&1)
42+
}
43+
}

0 commit comments

Comments
 (0)