Epic - Snake Sequence
2015-06-14 10:48
295 查看
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),并维护最大值。
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
相关文章推荐
- 【LeetCode】Implement Stack using Queues 解题报告
- WebRequest 对象的使用
- Distinct Subsequences
- Unique Paths
- looper、handler、messagequeue 总结
- Distinct Subsequences
- JDeveloper 配置 No suitable driver
- [ocUI日记]UIImage和UIImageview
- IOS UIKit 框架类之视图动画和坐标系介绍
- 【Android UI设计】Dialog对话框详解(一)
- iOS9 新增 UIStackView 官方文档翻译
- CS193p Lecture 11 - UITableView, iPad
- CS193p Lecture 10 - Multithreating, UIScrollView
- 基于链表实现Java 自定义Queue队列
- Android 之 Looper、MessageQueue、Handler 与消息循环
- java UID 问题
- VirtrueBox 镜像压缩
- [Algorithms] Longest Common Subsequence
- 理解MiniGUI消息循环和窗口过程
- Using JavaFX UI Controls 18 超链接