这基本上是一个动态编程问题。由于路径的细节不会影响未来的决策,因此您不必在每一步都考虑所有可能的路径。对于每个细胞,如果你走特定方向并采取特定数量的移动,则需要知道可以收集的最大量。没有别的因素影响你的决定
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被memoized,那么你得到一个相当有效的解决方案,因为可能性的数量是相对有限的。
虽然将它作为一个动态编程问题来处理会让你更有效。
@Radu:标签[算法]意味着确切的语言对于OP来说并不重要,只要描述该算法即可。 – Vlad
这是什么意思? :) – user1577191
另请参阅[问题#12712575](http://stackoverflow.com/questions/12712575/an-interesting-algorithm-need-pseudocode) –