Epic - Snake Sequence

本文介绍了一种基于动态规划算法解决寻找网格中蛇形数列的问题。蛇形数列是指网格中的相邻数字序列,每个数字与其右侧或下方的数字之差的绝对值为1。文章提供了详细的算法实现步骤,并通过一个具体的示例来展示如何找到最长的蛇形数列及其长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

转载于:https://www.cnblogs.com/lilixu/p/4574745.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值