深度优先搜索之迷宫问题

思路:确保在该点应该做什么,要做什么条件判断

import copy
#[0,0] ->[0,1]  x+0 y+1
map_list = [
    [0,0,0,0,0],
    [0,0,1,0,0],
    [0,0,0,1,0],
    [0,0,1,0,1],
    [0,1,0,2,0],
    [0,0,0,0,0],
    [0,1,1,0,0]
]
min = 99999
x, y = 0, 0#起始位置
#四个方向
next = [[0,1],[1,0],[0,-1],[-1,0]]#分别为右下左上     0,0
#标记已经走过的位置
book_list = []
#结果集
#将当前坐标和已走步数传进去
def dfs(x=0,y=0,step=0):
    global min,result
    #是否到终点??
    if map_list[x][y] == 2:
        # 确保result是最短的那条路
        if step<min:
            min = step
            #由于此时最后一点还没加入到列表,所以....
            book_list.append((x, y))
            result = copy.deepcopy(book_list)
            book_list.remove((x, y))
        #已经到达,不需要继续往下走
        return
    for i in range(4):#循环四次,依次尝试四个方向
        book_list.append((x, y))
        #y代表x轴
        ty = y + next[i][1]
        #x代表的时y轴
        tx = x + next[i][0]
        #tx 1  ty 0
        #判断该点是否可走,即是不是越界或者障碍物
        if 0<=tx<=6 and 0<=ty<=4 and (tx,ty) not in book_list:
            if  map_list[tx][ty] !=1:
                dfs(tx,ty,step+1)
            #将本次尝试移出
        book_list.remove((x,y))
if __name__ == '__main__':
    dfs()
    print(result)

猜你喜欢

转载自blog.csdn.net/wang785994599/article/details/81416444
今日推荐