簡體   English   中英

Python回溯問題,達到最大遞歸深度

[英]Python backtracking problem, maximum recursion depth reached

給定一個m*n停車場,停車場有幾輛車,每輛車如下:

car=[i,j,w,h,direction]
#i,j are top left position
#w,h are width and height
#direction can be -1/1 for horizontal/vertical
#horizontal cars can only move left or right
#vertical cars can only move up and down
#move one step at a time

在邊緣或網格處有一個出口

exit=[i,j]
#i=0 or m-1
#j=0 or n-1

所以問題是要找出特定的汽車是否可以駛出停車場。 我的想法是用遞歸來解決,如下

grid=[[0]*n for _ in range(m)]

#use dict to store cars info
cars={'car0':[i,j,w,h,dir],'car1':[...],'target_car':[...]}

#and a function to determine if it's possible to move a car in a certain direction
#which will return True if I can move cars[car_name] one step to move_direction
#false otherwise
is_valid_move(car_name,move_direction)

#and I have a function to actually move the car if previous function return True
move_car(car_name,direction) 

and now here is the function to solve the problem
def solver(grid,cars):
    #base cases
    if (some basic conditions):
        return True or False based on condition
    
    #otherwise, we try to move one car at a time
    for car_name in cars.keys():
        if is_valid_move(car_name,direction):
            move_car(car_name,direction)
            if solver(gird,cars):
                return True
            #just recover the parking gird
            move_car(car_name,inverse_direction)
        if is_valid_move(car_name,inverse_direction):
            move_car(car_name,inverse_direction)
            if solver(gird,cars):
                return True
            #just recover the parking gird
            move_car(car_name,direction)
    return False

如您所見,它無法正常工作,因為它會來回移動一輛車,直到達到最大遞歸深度。 我不確定如何處理它,也許有一種方法可以枚舉所有獨特的網格並逐一檢查它們。

確認一下,這是一款名為“高峰時間”的益智游戲的通用版本。

您需要將此視為圖遍歷問題。 每個棋盤位置都是圖的一個節點; 一次移動表示兩個節點之間的邊。

您必須實現一種算法來遍歷此圖,搜索解決方案狀態的路徑。 這是一個眾所周知的范式; 你有一些研究要做。 要包含的關鍵部分是避免訪問您已經看到的任何節點。 這是避免任何循環的最簡單方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM