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)

语法知识记录

相关推荐
迅猛龙办公室6 分钟前
python实现倒序输出数字
开发语言·python
全栈练习生9 小时前
AI Agent 沙箱
python·ai
SEO_juper10 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
用户83562907805112 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
for_ever_love__12 小时前
MySQL 全文索引实战:FULLTEXT、ngram 中文分词与 MATCH AGAINST 到底该怎么用
java·python·mysql·全文检索·分词·索引·ngram
用户83562907805112 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
weixin_4617694012 小时前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter
2601_9669496513 小时前
多市场量化策略的数据接口应该如何设计:从数据层架构到策略接入
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
全栈弄潮儿13 小时前
Python实战第1期:Python环境搭建与第一个程序
python
心易行者13 小时前
Agent应用+API端点商业化进阶实战:从单体智能体到可付费调用的API全流程
运维·服务器·人工智能·python·apache