You are given a grid of numbers. A snakes Equence is made up of adjacent numbers such, and 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 the 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 is multiple snake sequences with the Maximu M length).
Simple dynamic planning, using an array of the same size to record the length of the point to Snake sequence (default is 1), and maintain the maximum value.
defSnake (Matrix)return0ifmatrix.empty? M, n=matrix.length, matrix[0].length dp= Array.new (M) {array.new (n,1)} ans=-1m.times Do|i|n.times Do|j|Dp[i][j]= Dp[i-1][j] + 1ifI > 0 and(Matrix[i-1][j]-matrix[i][j]). ABS = = 1Dp[i][j]= Dp[i][j-1] + 1ifJ > 0 and(Matrix[i][j-1]-matrix[i][j]). ABS = = 1ans=[Ans,dp[i][j]].max end End Ansend
Epic-snake Sequence