题解 | #迷宫问题#

迷宫问题

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

import sys

result_path = []

def is_pos_legal(i:int, j:int, n:int, m:int):

    return 0 <= i < n and 0 <= j < m

def avail(maze:list[list[int]], i:int, j:int, n:int, m:int):

    return is_pos_legal(i, j, n, m) and maze[i][j] == 0

def need_visit(maze:list[list[int]], i:int, j:int, n:int, m:int, visited:set):

    return avail(maze, i, j, n, m) and (i, j) not in visited

def search(maze:list[list[int]], cur_path:list, i:int, j:int, n:int, m:int, visited:set):

    visited.add((i, j))

    cur_path.append((i, j))

    if i == n - 1 and j == m - 1:

        return True

    if need_visit(maze, i - 1, j, n, m, visited):

        if search(maze, cur_path, i - 1, j, n, m, visited):

            return True

    if need_visit(maze, i + 1, j, n, m, visited):

        if search(maze, cur_path, i + 1, j, n, m, visited):

            return True

    if need_visit(maze, i, j + 1, n, m, visited):

        if search(maze, cur_path, i, j + 1, n, m, visited):

            return True

    if need_visit(maze, i, j - 1, n, m, visited):

        if search(maze, cur_path, i, j - 1, n, m, visited):

            return True

    cur_path.pop()

    return False

stack = []

n, m = [int(i) for i in input().split()]

visited = set()

maze = [[int(i) for i in input().split()] for i in range(n)]

search(maze, result_path, 0, 0, n, m, visited)

print("\n".join(["({},{})".format(i[0], i[1]) for i in result_path]))

全部评论

相关推荐

整顿职场的柯基很威猛:这种不可怕,最可怕的是夹在一帮名校里的二本选手,人家才是最稳的。
点赞 评论 收藏
分享
joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务