自学内容网 自学内容网

11.12.2024刷华为OD-集合的使用,递归回溯的使用

HJ41 集合的使用

链接代码

HJ43 迷宫问题–递归回溯的使用

在这里插入图片描述

def dfs(x, y, path, grid):
    n = len(grid)
    m = len(grid[0])
    if x == n-1 and y == m-1:
        for cor in path:
            print("({},{})".format(cor[0],cor[1]))




    # 判断条件:1不能越界 2不能撞墙 3走过的不能走
    if 0 <= x+1 < n and 0 <= y < m and grid[x+1][y] != 1:
        path.append((x+1, y))
        grid[x+1][y] = 1
        dfs(x+1, y, path, grid)
        path.pop()
        grid[x + 1][y] = 0
    if 0 <= x-1 < n and 0 <= y < m and grid[x-1][y] != 1:
        path.append((x-1, y))
        grid[x-1][y] = 1
        dfs(x-1, y, path, grid)
        path.pop()
        grid[x - 1][y] = 0
    if 0 <= x < n and 0 <= y+1 < m and grid[x][y+1] != 1:
        path.append((x, y+1))
        grid[x][y+1] = 1
        dfs(x, y+1, path, grid)
        path.pop()
        grid[x][y + 1] = 0
    if 0 <= x < n and 0 <= y-1 < m and grid[x][y-1] != 1:
        path.append((x, y-1))
        grid[x][y-1] = 1
        dfs(x, y-1, path, grid)
        path.pop()
        grid[x][y - 1] = 0






if __name__ == "__main__":


    n, m = map(int, input().split())
    grid = []
    for _ in range(n):
        grid.append(list(map(int, input().split())))
    # print(grid)
    path = [(0, 0)]
    grid[0][0] = 1
    dfs(0,0,path, grid)

语法知识记录


原文地址:https://blog.csdn.net/qq_19875729/article/details/143724273

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!