题解 | #走迷宫#
走迷宫
https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64
n, m = map(int, input().split()) x1, y1, x2, y2 = map(int, input().split()) xs, ys, xt, yt = x1 - 1, y1 - 1, x2 - 1, y2 - 1 # 定义地图 l = [] for _ in range(n): l.append(list(input())) # 定义地图每个点到起点的最短距离 dist = [] for _ in range(n): dist.append([m*n] * m) def isValid(a, l, dist): return a[0] >= 0 and a[0] < n and a[1] >= 0 and a[1] < m and l[a[0]][a[1]] == '.' and dist[a[0]][a[1]] == m*n dist[xs][ys] = 0 path = [] path.append([xs, ys]) isFound = False while path: if path[0] == [xt, yt]: print(dist[xt][yt]) isFound = True break [x, y] = path.pop(0) if isValid([x, y + 1], l, dist): path.append([x, y + 1]) dist[x][y + 1] = dist[x][y] + 1 if isValid([x, y - 1], l, dist): path.append([x, y - 1]) dist[x][y - 1] = dist[x][y] + 1 if isValid([x + 1, y], l, dist): path.append([x + 1, y]) dist[x + 1][y] = dist[x][y] + 1 if isValid([x - 1, y], l, dist): path.append([x - 1, y]) dist[x - 1][y] = dist[x][y] + 1 if not isFound: print(-1)