题解 | 迷宫问题

迷宫问题

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

from collections import deque

h,w = map(int,input().split())
grid = [list(map(int,input().split())) for _ in range(h)]
visit = [[False]*w for _ in range(h)]
dxy = [(-1,0),(1,0),(0,-1),(0,1)]
path = []

q = deque()
q.append((0,0))
visit[0][0]=True

step = 0
def print_path():
    for x,y in path:
        print(f"({x},{y})")

def dfs(x,y):
    visit[x][y]=True
    path.append((x,y))
    if x==h-1 and y==w-1:
        print_path()
        return
    for dx,dy in dxy:
        nx = x + dx
        ny = y + dy
        if 0<=nx<h and 0<=ny<w:
            if not visit[nx][ny] and grid[nx][ny]==0:
                dfs(nx,ny)
                visit[nx][ny]=False
                path.pop()

dfs(0,0)


        

全部评论

相关推荐

04-13 09:56
已编辑
嵌入式工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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