题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

from collections import deque

n,m=map(int,input().split())
lst=[[]]*n

for i in range(n):
    lst[i]=input().split()
parent_map={}
pq=deque([(0,0)])
visited={(0,0)}
while pq:
    current_x,current_y=pq.popleft()
    for neix,neiy in[(current_x+1,current_y),(current_x,current_y+1),(current_x-1,current_y),(current_x,current_y-1)]:
        if neix==n or neiy==m or neix==-1 or neiy==-1:
            continue
        if lst[neix][neiy]=="0":
            if (neix,neiy) not in visited:
                visited.add((neix,neiy))
                pq.append((neix,neiy))
                parent_map[(neix,neiy)]=(current_x,current_y)
                if neix==n-1 and neiy==m-1:
                    path=[(neix,neiy)]
                    while path[-1]!=(0,0):
                        path.append(parent_map[path[-1]])
                    path.reverse()
                    for i in path:
                        print("(",i[0],",",i[1],")",sep="")
                    break




全部评论

相关推荐

你背过凌晨4点的八股文么:简历挂了的话会是流程终止,像我一样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务