题解 | #走迷宫#

走迷宫

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)

全部评论

相关推荐

代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务