题解 | 迷宫问题

迷宫问题

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

from collections import deque
'''import sys
h,w=map(int,input().split())
maze=[list(map(int,input().split())) for _ in range(h)]
visited=[[False]*w for _ in range(h)]
path=[]
#print(maze)
def dfs(x,y):
    if (not (x>=0 and x<h and y>=0 and y<w) or visited[x][y]==True or maze[x][y]!=0):
        return False
    path.append((x,y))
    visited[x][y]=True
    if(x==h-1 and y==w-1):
        return True
    for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)]:
        #print(dx,dy)
        if(dfs(x+dx,y+dy)):
            return True
    path.pop()
    return False
dfs(0,0)
for x,y in path:
    print('('+str(x)+','+str(y)+')')'''

import sys
h,w = map(int,input().split())
maze=[list(map(int,input().split())) for _ in range(h)]
visited=[[False]*w for _ in range(h)]
parent=[[None]*w for _ in range(h)]
def bfs():
    queue= deque()
    queue.append((0,0))
    visited[0][0]=True
    while(queue):
        x,y=queue.popleft()
        if(x==h-1 and y==w-1):
            break
        for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)]:
            #print(dx,dy)
            nx,ny=x+dx,y+dy
            #print(nx,ny)
            if(nx>=0 and nx<h and ny>=0 and ny<w) and maze[nx][ny]==0 and visited[nx][ny]==False:
                visited[nx][ny]=True
                queue.append((nx,ny))
                parent[nx][ny]=(x,y)
    x,y=h-1,w-1
    path=[]
    while ((x,y)!=(0,0)):
        path.append((x,y))
        x,y=parent[x][y]
    path.append((0,0))
    path.reverse()
    return path
path=bfs()
for x,y in path:
    print(f'({x},{y})')

注释的是DFS,下面是BFS。

BFS是最短路径,DFS不是。

DFS比较好写,一个递归调用。

BFS麻烦点

全部评论

相关推荐

01-05 09:14
同济大学 Java
不要盒我呀:我要是9✌🏻我就选保研,保研了大四再找实习,实习之后,如果觉得自己不适合互联网工作模式,还能有其他选择,如果实习后决定了走互联网,也能提升学历提高竞争力
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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