-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS求解迷宫最短路径
58 lines (51 loc) · 2.1 KB
/
BFS求解迷宫最短路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Maze:
def __init__(self,map,n,m,x,y):
self.ans=0
self.map=map
self.n=n
self.m=m
self.x=x
self.y=y
class Solution:
def solveMaze(self,maze): #宽度优先搜索求走出迷宫的最短长度
maze.ans=0
que=[(maze.x,maze.y,maze.ans)] #设置一个队列存放结点
visit={(maze.x,maze.y):True} #visit存放该结点是否被访问过
while len(que)>0 : #队列不为空时
node=que[0] #出队一个结点
del que[0]
x=node[0]
y=node[1]
ans=node[2]
if x==0 or x==maze.n-1 or y==0 or y==maze.n-1: #走到出口时更新数据
if maze.ans==0 or maze.ans>ans:
maze.ans=ans
#满足条件的结点入队
if x + 1 >= 0 and x + 1 < maze.n and y >= 0 and y < maze.m and (x + 1, y) not in visit and maze.map[x + 1][
y] == 1:
que.append((x + 1, y, ans + 1))
visit[(x + 1, y)] = True
if x >= 0 and x < maze.n and y + 1 >= 0 and y + 1 < maze.m and (x, y + 1) not in visit and maze.map[x][
y + 1] == 1:
que.append((x, y + 1, ans + 1))
visit[(x, y + 1)] = True
if x - 1 >= 0 and x - 1 < maze.n and y >= 0 and y < maze.m and (x - 1, y) not in visit and maze.map[x - 1][
y] == 1:
que.append((x - 1, y, ans + 1))
visit[(x - 1, y)] = True
if x >= 0 and x < maze.n and y - 1 >= 0 and y - 1 < maze.m and (x, y - 1) not in visit and maze.map[x][
y - 1] == 1:
que.append((x, y - 1, ans + 1))
visit[(x, y - 1)] = True
return maze.ans #返回最终求解的最短长度
if __name__ == '__main__':
raw = input().split('\n')[0].strip().split(' ')
n = int(raw[0])
m = int(raw[1])
map = [[int(raw) for raw in input().split('\n')[0].strip().split(' ')] for i in range(n)]
raw = input().split('\n')[0].strip().split(' ')
x = int(raw[0])
y = int(raw[1])
maze = Maze(map, n, m, x, y)
sol = Solution()
print (sol.solveMaze(maze))