繁体   English   中英

最短路径算法递归

[英]shortest path algorithm recursion

作为编程练习,我正在尝试用Python解决一个益智游戏。 为此,我使用了递归算法,我认为这是深度优先搜索的实现。 我的问题是,达到最大递归限制时出现运行时错误,但我还没有弄清楚如何解决它。

我看到了有关游戏和算法的不同文章,但我不想在这种设置下重新编码,而是希望对我编写的内容有所帮助。 所以这是我的代码的伪简化版本。

# Keep track of paths that I have found for given states. 
best_paths = dict()

def find_path(state, previous_states = set()):

  # The output is a tuple of the length of the path and the path.
  if state in previous_states:
    return (infty,None)
  previous_states = copy and update with state

  if state in target_states: 
    best_paths[state] = (0,[])

  if state in best_paths:
    return best_paths[state]

  possible_moves = set((piece,spaces) that can be moved)
  (shortest_moves,shortest_path) = (infty,None)
  for (piece,spaces) in possible_moves:
    move_piece(piece,spaces)
    try_state = the resulting state after moving the piece
    (try_moves,try_path) = find_path(try_state,previous_states)

    if try_moves < shortest_moves:
      shortest_moves = try_moves + 1
      shortest_path  = try_path + [(piece,spaces)]

    # Undo the move for the next call
    move_piece(piece,-spaces)

  if shortest_moves < infty:
    best_paths[state] = shortest_path

  return (best_moves, shortest_path)

所以我的问题是,如果在for循环之外有返回值,是什么导致递归达到最大值?
谢谢您的帮助。

    --

如果遇到递归深度超出异常,则可能是代码问题或需要其他算法。 看来您的算法是O(N * N),其中N是节点数。 N不需要太大就可以达到极限。

有更好的方法来解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM