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)

语法知识记录

相关推荐
数据科学小丫1 小时前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL1 小时前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
查古穆2 小时前
python进阶-Pydantic模型
开发语言·python
佳木逢钺3 小时前
PyQt界面美化系统高级工具库:打造现代化桌面应用的完整指南
python·pyqt
工頁光軍3 小时前
基于Python的Milvus完整使用案例
开发语言·python·milvus
Csvn3 小时前
特殊方法与运算符重载
python
xht08323 小时前
PHP vs Python:编程语言终极对决
开发语言·python·php
2401_879693874 小时前
使用Python控制Arduino或树莓派
jvm·数据库·python
查古穆4 小时前
python进阶-推导式
开发语言·python