Leetcode 0037.sudoku-solver(python)
37. Sudoku Solver
题目
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
- Each of the digits
1-9must occur exactly once in each row. - Each of the digits
1-9must occur exactly once in each column. - Each of the digits
1-9must occur exactly once in each of the 93x3sub-boxes of the grid.
The '.' character indicates empty cells.
Example 1:
1 | Input: 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"]] |
Constraints:
board.length == 9board[i].length == 9board[i][j]is a digit or'.'.- It is guaranteed that the input Sudoku will have exactly one solution.
题目大意
编写一个程序通过填充空单元格来解决数独问题。数独解必须满足:每行、每列、每个 3x3 子网格中数字 1-9 恰好出现一次。
解题思路
方法一:基础回溯法
思路
使用回溯算法求解数独问题。回溯算法的核心思想是:尝试在当前空单元格填入一个数字,检查是否有效,如果有效则继续下一个单元格,否则撤销当前操作并尝试下一个数字。
复杂度分析
- 时间复杂度:O(9^(空格数)),每个空格有 9 种选择。
- 空间复杂度:O(1),递归深度最大为空格数。
方法二:启发式搜索 + 最小堆(最优解)
方法来源:灵茶山艾府 - 数独?要玩题目就要玩透!
出处:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。2025年09月22日修改
思路
使用 MRV(Minimum Remaining Values)启发式搜索配合最小堆优化:
- 预记录空格位置:记录所有空格子的位置和每个格子的候选数字数量
- 最小堆优先:使用
heapq实现最小堆,优先处理候选数最少的格子 - 动态更新:每次尝试后重新计算候选数,若失败则重新入堆
这种方法能在搜索树的早期就剪枝,大幅减少搜索空间,对于困难数独效果尤为显著。
复杂度分析
- 时间复杂度:大幅剪枝后的 O(9^(空格数)),实际运行速度提升 100-1000 倍。
- 空间复杂度:O(n),n 为空格数,用于堆存储。
代码实现
方法一:基础回溯法
1 | from typing import List |
方法二:启发式搜索 + 最小堆(推荐)
1 | from typing import List |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

