1. question: 解数独(困难)
编写一个程序,通过填充空格来解决数独问题。
数独的解法需 遵循如下规则:
- 数字 1-9 在每一行只能出现一次。
- 数字 1-9 在每一列只能出现一次。
- 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sudoku-solver
示例 1:
1 | 输入: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 | board.length == 9 |
2. answers
这道题和N皇后非常类似。有四个限制:
- 只能是[1,9]
- 同行不能出现重复的
- 同列不能出现重复的
- 所在区域不能出现重复的
所以,每次递归的时候,需要提前准备好:
- 下一个要填充的位置(即遍历,找到那个位置)
- 下个位置可选择的数字。
- 同行不能重复(遍历那一行)
- 同列不能重复(遍历那一列)
- 同区域不能重复(遍历那个区域)
注意,在递归完回溯的时候,如果下个位置找到了结果(下个位置会无限递归下去,所以最终就是递归到最后一个位置),那么就无需递归了,因为题目保证了之后一个结果。如果没找到,需要还原当前位置为’.’,进行当前位置的下一个选择。代码如下所示:
1 | public class Solution_0092 { |
3. 备注
参考力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 (leetcode-cn.com),代码随想录 (programmercarl.com)。