这基本上是一个动态规划问题。您实际上不必在每一步都考虑所有可能的路径,因为路径的细节不会影响未来的决策。对于每个单元格,您需要知道如果您朝特定方向移动并采取特定数量的移动,则可以收集的最大数量。没有其他因素会影响您的决定。
def bestAmount(x,y,direction,n_moves):
# If this position is off the grid, then this isn't a valid state
if x<0 or x>=width or y>=height:
return None
if n_moves==0:
# We came to the last move.
if y!=height-1:
# If we're not at the bottom row then this isn't a valid path.
return None
# Otherwise, the final cell value is part of our total.
return cellValue(x,y)
if direction=='down':
# If we came down to get to this position, then the next move
# can be either left, right, or down
left = bestAmount(x-1,y,'left',n_moves-1)
right = bestAmount(x+1,y,'right',n_moves-1)
down = bestAmount(x,y+1,'down',n_moves-1)
return max(left,right,down)+cellValue(x,y)
if direction=='left':
# If we moved left to get to this position, then
# we can't go right, since we would be visiting the same position again.
left = bestAmount(x-1,y,'left',n_moves-1)
down = bestAmount(x,y+1,'down',n_moves-1)
return max(left,down)+cellValue(x,y)
if direction=='right':
# same logic as for left, but opposite.
right = bestAmount(x+1,y,'right',n_moves-1)
down = bestAmount(x,y+1,'down',n_moves-1)
return max(right,down)+cellValue(x,y)
def solve(n_moves):
# Start by pretending we entered the starting cell by going down
return bestAmount(0,0,'down',n_moves)
如果 bestAmount 被记忆,那么你会得到一个相当有效的解决方案,因为可能性的数量相对有限。
不过,将其视为动态规划问题将为您提供更有效的解决方案。