题解 | 迷宫问题

迷宫问题

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

import sys

row,col = map(int,sys.stdin.readline().strip().split())
lines = sys.stdin.readlines()
matrix = []
path = []
for line in lines:
    matrix.append(list(map(int,line.strip().split())))

def maze(x,y):
    """从x行y列出发能否走到终点"""

    # 位置是否合法,若合法加入path
    if x < 0 or x > row - 1 or y < 0 or y > col - 1 or matrix[x][y] == 1:
        return False
    path.append([x,y])

    # 终点判定
    if x == row - 1 and y == col - 1:
        return True

    # 标记走过的路
    matrix[x][y] = 1

    for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
        if maze(x+dx,y+dy):
            return True
    
    # 只有所有的for都没走通时才弹出
    path.pop() 

    # 走到最后仍未判定终点,则说明无法到达终点
    return False

if maze(0,0):
    for position in path:
        print(f"({position[0]},{position[1]})")

二刷错误点:

1.判定位置合法应该放在最开始执行,不合法就返回False

2.弹出path的位置:应该在for循环执行完之后,for循环执行完仍未返回True则说明走不通,弹出当前位置

3.赋值等号'='写成了'=='

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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