[英]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.