题解 | 走迷宫

走迷宫

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

from collections import defaultdict
from collections import deque
def main():
    n,m=list(map(int,input().split()))
    startr,startc,endr,endc=list(map(int,input().split()))
    maps=[]
    for _ in range(n):
        maps.append(list(input()))
    #print(maps)
    T,F='.','*'
    def neibor(r,c):
        moves={(r-1,c),(r+1,c),(r,c-1),(r,c+1)}
        for r,c in moves:
            if r in range(n) and  c in range(m) and maps[r][c]==T:
                maps[r][c]=F
                yield (r,c)

    de=deque()
    counts=0
    de.append((startr-1,startc-1,counts))
    parent=defaultdict(lambda:float('inf'))
    while de:
        r,c,counts=de.popleft()
        for x,y in neibor(r,c):
            de.append((x,y,counts+1))
            if parent[(x,y)]>counts+1:
                parent[(x,y)]=counts+1
    res=parent[(endr-1,endc-1)]
    print(res if res!=float('inf') else -1)





if __name__=='__main__':
    main()

全部评论

相关推荐

吴offer选手:学到了,下次面试也放张纸在电脑上,不然老是忘记要说哪几个点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务