题解 | #迷宫问题#

迷宫问题

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]))

全部评论

相关推荐

11-14 16:13
已编辑
重庆科技大学 测试工程师
Amazarashi66:不进帖子我都知道🐮❤️网什么含金量
点赞 评论 收藏
分享
我是小红是我:学校换成中南
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务