|
发表于 2023-10-2 16:14:50
|
显示全部楼层
# -*- coding: utf-8 -*-
#python 3.8
"""
Created on Wed Nov 4 21:12:02 2020
One is Never too old to learn.
@author: NicholasTU
"""
def foo(n,ar):
"""
动态规划解青蛙跳荷叶
m_l 为状态映射:l->n
l为某一状态,状态标识方式为l[0]为当前青蛙位置,取1-n,
l[1:]为荷叶间剩余跳跃次数
n为该状态下青蛙最多跳几次
"""
m_l = dict()
def find(l):
nonlocal m_l
if l not in m_l:
#青蛙位于左边界情况
if l[0] == 1:
if l[l[0]] == 0:
#无路可走,状态映射为0
m_l[l] =0
else:
#右跳一步作为下一状态,当前状态映射为下一状态步数+1
l2 = list(l[1:])
l2[0] -=1
l2 = tuple([2]+l2)
m_l[l] = find(l2)+1
#青蛙位于右边界情况
elif l[0] == n:
if l[n-1] ==0:
#无路可走,状态映射为0
m_l[l] =0
else:
#左跳一步作为下一状态,当前状态映射为下一状态步数+1
l2 = list(l[1:])
l2[n-2] -=1
l2 = tuple([n-1]+l2)
m_l[l] = find(l2)+1
#青蛙位于中间状态
else:
if l[l[0]] == 0 and l[l[0]-1] == 0:
#无路可走,状态映射为0
m_l[l] = 0
elif l[l[0]-1] == 0:
#右侧无路,左跳一步作为下一状态,当前状态映射为下一状态步数+1
l3 = list(l[1:])
l3[l[0]-1] -= 1
l3 = tuple([l[0]+1,]+l3)
m_l[l] = find(l3)+1
elif l[l[0]] == 0:
#左侧无路,右跳一步作为下一状态,当前状态映射为下一状态步数+1
l2 = list(l[1:])
l2[l[0] - 2] -= 1
l2 = tuple([l[0]-1,]+l2)
m_l[l] = find(l2) +1
else:
#左右各跳一部作为下一状态,当前状态映射为下一状态步数较大一状态值+1
l2 = list(l[1:])
l2[l[0] - 2] -= 1
l2 = tuple([l[0]-1,]+l2)
l3 = list(l[1:])
l3[l[0]-1] -= 1
l3 = tuple([l[0]+1,]+l3)
m_l[l] = max(find(l2),find(l3))+1
return m_l[l]
ans = list()
for i in range(n):
ans.append(find(tuple([i+1]+list(ar))))
return max(ans)
print(foo(10,(2,18,2,8,2,6,2,5,7)))
====================================
输出:52
提示:从第10片叶子出发按(10, 9, 10, 9, 10, 9, 10, 9, 8, 9, 8, 9, 8, 7, 6, 7, 6, 7, 6, 5, 4, 5, 4, 5, 4, 5, 4, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8)的次序跳跃。 |
|