原理为深度优先搜索算法。
import matplotlib.pyplot as plt
import numpy as np
# 深度优先搜索
map = np.array(
[[0,1,1,1,1,1,1,1,1,1],
[0,1,1,1,0,1,1,1,0,1],
[0,0,0,1,0,0,0,0,0,1],
[1,1,0,1,0,1,0,1,1,1],
[1,1,0,0,0,1,0,1,1,1],
[1,0,0,1,1,1,0,0,0,1],
[1,1,1,1,0,0,0,1,1,1],
[1,1,0,1,0,1,1,0,0,0],
[1,0,1,1,0,0,0,0,1,0],
[1,0,1,1,1,1,1,1,1,0],]
)
start = (0, 0)
end = (9, 9)
track = [start] # 记录轨迹
list01 = [start] # 标记已经走过的点
while list01:
now = track[-1]
if now == end:
print(list01)
break
row, col = now
if ((row - 1)>=0) and ((map[row - 1, col]==0) and ((row - 1, col) not in list01)): # up
list01.append((row - 1, col))
track.append((row - 1, col))
continue
elif ((col + 1)<=9) and ((map[row, col + 1]==0) and ((row, col + 1) not in list01)): # right
list01.append((row, col + 1))
track.append((row, col + 1))
continue
elif ((row + 1)<=9) and ((map[row + 1, col]==0) and ((row + 1, col) not in list01)): # down
list01.append((row + 1, col))
track.append((row + 1, col))
continue
elif ((col - 1)>=0) and ((map[row, col - 1]==0) and ((row, col - 1) not in list01)): # left
list01.append((row, col - 1))
track.append((row, col - 1))
continue
else:
try:
track.pop()
except:
print("无路可走")
break
# # Plot track
# for x,y in track:
# map[x,y] = 2
plt.imshow(map)
地图
搜索到的路径
所有探索过的路径