当前位置 博文首页 > wang785994599的博客:广度优先搜索迷宫问题

    wang785994599的博客:广度优先搜索迷宫问题

    作者:[db:作者] 时间:2021-09-06 18:59

    用二维数据构造一个迷宫,求到某点的最短路径。

    思路:到达每点后,依次将下一步可达点放入一个数组,将走过的点放入一个路过数据,每次循环,遍历完一个点,指针后移,遍历后面的点。

    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]
    ]
    #自定义坐标节点,用于记录某点的信息
    class Node(object):
        def __init__(self,x,y,step,father=None):
            self.x = x
            self.y = y
            self.step = step
            self.father = father
    #初始点
    start = Node(0,0,0,None)
    #可达列表,初始为start
    can_arrive = [start]
    #已走点
    book_list = []
    #四个方向
    next = [[0,1],[1,0],[0,-1],[-1,0]]
    #结果集
    result = []
    
    def bfs():
        flag = True
        while flag:
            for i in range(10000):
                #获得该点
                x,y,step = can_arrive[i].x,can_arrive[i].y,can_arrive[i].step
                book_list.append((x,y))
                # 该点是终点
                if map_list[x][y] == 2:
                    #依次遍历父节点,获取坐标,逆置后返回
                    node = can_arrive[i]
                    while node.father:
                        result.append((node.x,node.y))
                        node = node.father
                    result.reverse()
                    return result
                #遍历该点可达点
                for j in range(4): #先向右   [0,1]
                    tx = x + next[j][1]
                    ty = y + next[j][0]
                    if 0 <= tx <= 6 and 0 <= ty <= 4 and (tx, ty) not in book_list:
                        if map_list[tx][ty] != 1:
                            #该点可达,放入可达列表
                            can_arrive.append(Node(tx,ty,step+1,can_arrive[i]))
    if __name__ == '__main__':
        res = bfs()
        print(res)
    
    
    
    
    

    ?

    cs
    下一篇:没有了