1、建立迷宮地圖,可以用二維陣列表示,01分別表示牆和路
2、設定迷宮的起點和終點
3、將起點push進儲存路徑的棧。從棧頂元素開始,搜尋其上下左右格仔,如果可達,則將搜尋到的可達的格仔push到當前路徑中(並標記該格仔已經遍歷過),如果乙個格仔周圍的四個格仔均不可走,則將該格仔從路徑中pop()(並標記該格仔已經遍歷過)。重複上述過程
直到搜尋的格仔==終點(找到可通行的迷宮路徑),或者棧為空(不存在滿足條件的路徑)
具體**如下:
# -*- coding:utf-8 -*-
# author :dyl time:2020/5/3
#建立迷宮
#0代表牆,1road
import numpy as np
deffindpath
(mazemap,startpoint,endpoint)
: path =
# 儲存路徑
mapsize =
10 flag = np.zeros(
[mapsize, mapsize]
)# 標記遍歷過的路徑
if startpoint==endpoint:
return path
flag[startpoint[0]
][startpoint[1]
]=2 direction =[(
0,-1
),(0
,1),
(-1,
0),(
1,0)
]# 左右上下
while
len(path)
>0:
node=path[-1
] find=
0#標記node周圍的點有沒有可走路徑,初始,沒有
for d in direction:
i = node[0]
+ d[0]
j = node[1]
+ d[1]
if i >=
0and i < mapsize and j >=
0and j < mapsize and flag[i]
[j]==
0and mazemap[i]
[j]==1:
#節點可通if(
[i, j]
== endpoint)
:return path
else
: find=
1[i, j]
) flag[i]
[j]=
2break
if(find==0)
: path.pop(
)return
主函式:
if __name__==
"__main__"
: mazemap=[[
1,0,
0,0,
0,0,
0,0,
0,0]
,[1,
1,0,
0,1,
1,1,
0,1,
0],[
0,1,
1,1,
1,0,
1,0,
1,0]
,[0,
0,1,
0,0,
0,1,
1,1,
0],[
0,0,
1,1,
1,1,
0,0,
0,0]
,[0,
0,0,
0,0,
1,1,
1,0,
0],[
0,1,
1,1,
1,1,
0,1,
0,0]
,[0,
1,0,
1,0,
1,0,
1,1,
0],[
0,1,
1,1,
0,0,
0,0,
1,0]
,[0,
0,0,
0,0,
0,0,
0,1,
0]]#10*10
startpoint =[1
,0] endpoint =[9
,8] path=
path=findpath(mazemap,startpoint,endpoint)
if path==
:print
("can not find the path"
)else
:for p in path:
print
(p,'->'
,end='')
print
(endpoint)
newmaze=mazemap
for l in path:
#標記路徑為2
newmaze[l[0]
][l[1]
]=2for row in newmaze:
for e in row:
print(''
.format
(e),end='')
print
("\n"
)
執行結果如下:2代表找到的路徑
[1,
0]->[1
,1]-
>[2
,1]-
>[2
,2]-
>[3
,2]-
>[4
,2]-
>[4
,3]-
>[4
,4]-
>[4
,5]-
>[5
,5]-
>[5
,6]-
>[5
,7]-
>[6
,7]-
>[7
,7]-
>[7
,8]-
>[8
,8]-
>[9
,8]1
0000
0000
0220
0111
0100
2211
0101
0002
0001
1100
0222
2000
0000
0022
2000
1111
1020
0010
1010
2200
1110
0002
0000
0000
010[finished in
0.4s]
利用棧實現迷宮求解
如下是每個節點的資料結構 1 typedef struct direction 方向 78 typedef struct point 位置 1213 14 typedef struct stacknode linkstackptr 節點資料結構 鏈棧及基本操作實現 1 typedef struct ...
棧實現迷宮
棧的型別定義 棧是一種特殊的線性表,限定只能在表的一端進行插入和刪除操作的線性表。在表中,允許插入刪除的一端稱為 棧頂 不允許插入刪除的另一端稱為 棧底 沒有元素的棧稱為空棧,插入元素稱為入棧,刪除元素稱為出棧,稱為先進後出。順序棧型別的定義 順序棧的儲存方式是陣列,需要事先為他分配乙個可容納最多元...
利用棧求解迷宮問題
利用棧求解迷宮問題 源 include include define m 8 define n 8 define maxsize m n typedef struct box typedef struct sttype int mg m 2 n 2 bool mgpath int xi,int yi...