Python小练习系列 Vol.5:数独求解(经典回溯 + 剪枝)

🧠 Python小练习系列 Vol.5:数独求解(经典回溯 + 剪枝)

🧩 数独不仅是益智游戏,更是回溯算法的典范!本期我们将用 DFS + 剪枝 的方式一步步求解一个标准 9x9 数独。


🧩 一、题目描述

给定一个部分填充的 9×9 数独棋盘,请编写一个程序将其填完,使每行、每列、每个 3×3 宫内的数字 1~9 均不重复。

示例输入:

board = [
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]

🧠 二、解题思路

使用回溯 + 剪枝,依次尝试将数字 1~9 填入空格中,若不符合数独规则则回退重试。

核心逻辑:

  • 递归寻找空白格,尝试填入合法数字
  • 若数字在当前行、列或 3x3 宫格中已出现,则剪枝
  • 全部填满时即为解

👨‍💻 三、Python代码实现

def solve_sudoku(board):
    def is_valid(r, c, ch):
        for i in range(9):
            if board[r][i] == ch or board[i][c] == ch:
                return False
            box_r, box_c = 3 * (r // 3) + i // 3, 3 * (c // 3) + i % 3
            if board[box_r][box_c] == ch:
                return False
        return True

    def dfs():
        for i in range(9):
            for j in range(9):
                if board[i][j] == ".":
                    for ch in map(str, range(1, 10)):
                        if is_valid(i, j, ch):
                            board[i][j] = ch
                            if dfs():
                                return True
                            board[i][j] = "."
                    return False
        return True

    dfs()

📌 四、输出示例(运行后 board 被原地修改)

solve_sudoku(board)
for row in board:
    print(" ".join(row))

🧩 五、关键点总结

步骤说明
查找空位使用双层循环寻找 .
合法判断检查当前行、列、宫格是否冲突
回溯回退无法填充时,重置该位置为 .

✅ 本题是典型的「排列填空 + 剪枝」模型


💡 六、进阶挑战

  • 🧠 输出所有可能解(需去掉第一个 return)
  • ⚡ 加速优化:用位运算预处理可选值
  • 🎨 制作 GUI 数独求解器(Tkinter/PyQt)

❤️ 结语

数独是一道优雅的全排列题目,透过回溯 + 剪枝,掌握“选择-尝试-回退”的算法核心!

📌 下一期预告:单词搜索(网格回溯)


👉 点个赞 👍 + 收藏 🌟,学透回溯,从数独开始!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

滴答滴答滴嗒滴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值