题目:给定大小为n*m的矩阵,求S到G的最短路径并输出
输入:
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
输出:
迷宫路径
python代码
import queue
MAX_VALUE = float('inf')
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def bfs(maze, begin, end):
n, m = len(maze), len(maze[0])
dist = [[MAX_VALUE for _ in range(m)] for _ in range(n)]
pre = [[None for _ in range(m)] for _ in range(n)] # 当前点的上一个点,用于输出路径轨迹
nx = [[1,0],[-1,0],[0,-1],[0,1]]
sx, sy = begin.x, begin.y
gx, gy = end.x, end.y
dist[sx][sy] = 0
q = queue.Queue()
q.put(begin)
while q:
point = q.get()
if point.x == gx and point.y == gy:
break
for i in range(4):
dx, dy = point.x + nx[i][0], point.y + nx[i][1]
if 0<=dx<n and 0<=dy<m and maze[dx][dy] != '#' and dist[dx][dy] == MAX_VALUE:
dist[dx][dy] = dist[point.x][point.y] + 1
pre[dx][dy] = point
q.put(Point(dx, dy))
stack = []
curr = end
while True:
stack.append(curr)
if curr.x == begin.x and curr.y == begin.y:
break
prev = pre[curr.x][curr.y]
curr = prev
while stack:
curr = stack.pop()
print('(%d, %d)' % (curr.x, curr.y))
if __name__ == '__main__':
n, m = map(int, input().split())
maze = [['' for _ in range(m)] for _ in range(n)]
begin = Point()
end = Point()
for i in range(n):
s = input()
maze[i] = list(s)
if 'S' in s:
begin.x = i
begin.y = s.index('S')
if 'G' in s:
end.x = i
end.y = s.index('G')
bfs(maze, begin, end)
bfs找迷宫最短路径并输出 python
最新推荐文章于 2023-08-15 21:13:05 发布