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

文章目录

  • [HJ41 集合的使用](#HJ41 集合的使用)
  • [HJ43 迷宫问题--递归回溯的使用](#HJ43 迷宫问题--递归回溯的使用)
  • 语法知识记录

HJ41 集合的使用

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

python 复制代码
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)

语法知识记录

相关推荐
用户83562907805112 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805113 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生21 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师21 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码21 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf21 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780512 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent2 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python