Epic-snake Sequence

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.