python 迷宮問題


 

# -*- coding:utf-8 -*-
 
from collections import deque   # 引入隊列
 
maze = [
    [1,1,1,1,1,1,1,1,1,1],
    [1,0,0,1,0,0,0,1,0,1],
    [1,0,0,1,0,0,0,1,0,1],
    [1,0,0,0,0,1,1,0,0,1],
    [1,0,1,1,1,0,0,0,0,1],
    [1,0,0,0,1,0,0,0,0,1],
    [1,0,1,0,0,0,1,0,0,1],
    [1,0,1,1,1,0,1,1,0,1],
    [1,1,0,0,0,0,0,0,0,1],
    [1,1,1,1,1,1,1,1,1,1]
 ]
 
# 四個移動方向
dirs = [
    lambda x,y: (x+1, y),   # 下
    lambda x,y: (x-1, y),   # 上
    lambda x,y: (x, y-1),   # 左
    lambda x,y: (x, y+1)    # 右
]
 
 
def print_r(path):
    """打印路徑"""
    curNode = path[-1]    # 最后一個節點
    realpath = []         # 出去的路徑
    while curNode[2] != -1:   # 判斷最后一個節點的標記是否為-1,如果是-1說明是起始點,如果不是-1就繼續查找
        realpath.append(curNode[0:2])   # 拿到並添加節點x,y坐標信息
        curNode = path[curNode[2]]      # 這里curNode[2]是當前節點的前一步節點的標識:path的下標,因此path[curNode[2]]拿到前一節點
 
    realpath.append(curNode[0:2])       # 在這里curNode[2] == -1,是迷宮起點,將坐標信息加入路徑
 
    realpath.reverse()    # 將列表倒序,將前面生成的從后往前的列表變為從前往后
    print(realpath)
 
 
def maze_path_queue(x1, y1, x2, y2):   # (x1,y1)代表起點;(x2,y2)代表終點
    """用隊列實現迷宮問題——深度優先搜索"""
    queue = deque()   # 創建隊列
    queue.append((x1, y1, -1))    # 加入起點,第三個參數是記錄時誰讓它來的,這里起始點設置為-1
    path = []   # 保存出隊節點
    while len(queue) > 0:   # 只有隊不空就一直循環
        curNode = queue.pop()  # 隊首節點出隊,並存為當前節點變量
        path.append(curNode)   # 添加到path列表
        if curNode[0] == x2 and curNode[1] == y2:   # 判斷是否找到終點
            print_r(path)   # 如果到達終點,打印路徑
            return True
 
        for dir in dirs:    # 搜索四個方向
            nextNode = dir(curNode[0], curNode[1])    # curNode[0],curNode[1]分別是當前節點x、y
            if maze[nextNode[0]][nextNode[1]] == 0:   # 如果有路可走
                queue.append((nextNode[0], nextNode[1], len(path) - 1))   # 后續節點進隊,標記誰讓它來的:path最后一個元素的下標
                maze[nextNode[0]][nextNode[1]] = 2   # 設置為2,標記為已經走過
 
    else:   # 如果隊列為空(當前節點到了死路,節點刪除沒有新節點加入),沒有路
        print("沒有路")
        return False
 
 
maze_path_queue(1,1,8,8)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM