Skip to content

Commit d1f7488

Browse files
committed
0329
1 parent 578dfec commit d1f7488

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# @param {Integer[][]} matrix
2+
# @return {Integer}
3+
def longest_increasing_path(matrix)
4+
rows = matrix.size.freeze
5+
cols = matrix[0].size.freeze
6+
directions = [[1,0], [-1,0], [0,1], [0,-1]].freeze
7+
memo = Array.new(rows) { Array.new(cols) }
8+
dfs = lambda { |r, c|
9+
return memo[r][c] if memo[r][c]
10+
11+
max = 1
12+
directions.each { |dr, dc|
13+
next_r = r + dr
14+
next_c = c + dc
15+
if next_r >= 0 && next_c >= 0 && next_r < rows && next_c < cols && matrix[r][c] < matrix[next_r][next_c]
16+
max = [max, 1 + dfs.call(next_r, next_c)].max
17+
end
18+
}
19+
memo[r][c] = max
20+
}
21+
22+
longest = 0
23+
(0...rows).each { |r|
24+
(0...cols).each { |c|
25+
longest = [longest, dfs.call(r, c)].max
26+
}
27+
}
28+
29+
longest
30+
end

0 commit comments

Comments
 (0)