1. 程式人生 > >迷宮問題之廣搜

迷宮問題之廣搜

#!/usr/bin/python3
# 檔名: StackClasq.py
# 作者: 巧若拙
# 日期: 2018年12月14日
from QueueClass import ListQueue,LinkQueue

OPEN, CLOSE, PASSED, ROAD = 0, 1, 2, -1 #分別表示該點通,不通,已走和屬於所選路徑
dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) #分別向東南西北走的行列座標變換情況

def mark(maze, pos):
    maze[pos[0]][pos[1]] = PASSED

def passable(maze, pos):    #判斷當前位置是否可通行
    return maze[pos[0]][pos[1]] == OPEN


def print_path(start, end, path):#逆序輸出路徑
    print(end, end = " ")
    pos = path[end]
    while path[pos] != pos:
        print(pos, end = " ")
        pos = path[pos]
    print(start)

def extentSearch(maze, start, end): #用佇列實現廣度優先搜尋
    if start == end:
        print(start)
        return True
    q = LinkQueue()
    mark(maze, start)
    q.enqueue(start)
    path = {start: start} #用字典記錄其前驅位置
    while not q.is_empty():
        pos = q.dequeue()
        for i in range(4): #依次檢查四個方向
            nextp = (pos[0]+dirs[i][0], pos[1]+dirs[i][1])
            if passable(maze, nextp):
                mark(maze, nextp)
                q.enqueue(nextp)
                path[nextp] = pos
                if nextp == end:
                    print_path(start, end, path)
                    return True
        
    return False

start = (1, 1)                                       
end = (10, 12)
maze = [[1,1,1,1,1,1,1,1,1,1,1,1,1,1],
        [1,0,0,0,1,1,0,0,0,1,0,0,0,1],
        [1,0,1,0,0,0,0,1,0,1,0,1,0,1],
        [1,0,1,0,1,1,0,1,0,1,0,1,0,1],
        [1,0,1,0,0,0,0,0,0,1,1,1,0,1],
        [1,0,1,1,1,1,1,1,1,1,0,0,0,1],
        [1,0,1,0,0,0,0,0,0,0,0,1,0,1],
        [1,0,0,0,1,1,1,0,1,0,1,1,0,1],
        [1,0,1,0,1,0,1,0,1,0,1,0,0,1],
        [1,0,1,0,1,0,1,0,1,1,1,1,0,1],
        [1,0,1,0,0,0,0,0,0,0,0,0,0,1],
        [1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
print(extentSearch(maze, start, end))