You are given a grid of numbers. A snakes equence is made up of adjacent numbers such that for each number, the number on the right or the number below it is +1 or -1 its value. For example,
1 3 2 6 8
-9 7 1 -1 2
1 5 0 1 9
In this grid, (3, 2, 1, 0, 1) is a snake sequence. Given a grid, find the longest snake sequences and their lengths (so there can be multiple snake sequences with the maximum length).
简单的动态规划,使用一个相同大小的数组记录到snake sequence该点的长度(默认为1),并维护最大值。
def snake(matrix) return 0 if matrix.empty? m , n = matrix.length, matrix[0].length dp = Array.new(m){Array.new(n,1)} ans = -1 m.times do |i| n.times do |j| dp[i][j] = dp[i-1][j] + 1 if i > 0 and (matrix[i-1][j] - matrix[i][j]).abs == 1 dp[i][j] = dp[i][j-1] + 1 if j > 0 and (matrix[i][j-1] - matrix[i][j]).abs == 1 ans = [ans,dp[i][j]].max end end ans end
时间: 2024-10-15 08:08:14