解数独
- 题目
- 题目描述
- 示例 1:
- 提示:
- 题解
- 解题思路
- python代码
- 提交结果
题目
题目描述
编写一个程序,通过填充空格来解决数独问题。
数独的解法需 遵循如下规则:
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
示例 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”]]
输出:[[“5”,“3”,“4”,“6”,“7”,“8”,“9”,“1”,“2”],[“6”,“7”,“2”,“1”,“9”,“5”,“3”,“4”,“8”],[“1”,“9”,“8”,“3”,“4”,“2”,“5”,“6”,“7”],[“8”,“5”,“9”,“7”,“6”,“1”,“4”,“2”,“3”],[“4”,“2”,“6”,“8”,“5”,“3”,“7”,“9”,“1”],[“7”,“1”,“3”,“9”,“2”,“4”,“8”,“5”,“6”],[“9”,“6”,“1”,“5”,“3”,“7”,“2”,“8”,“4”],[“2”,“8”,“7”,“4”,“1”,“9”,“6”,“3”,“5”],[“3”,“4”,“5”,“2”,“8”,“6”,“1”,“7”,“9”]]
解释:输入的数独如上图所示,唯一有效的解决方案如下所示:
提示:
board.length == 9
board[i].length == 9
board[i][j] 是一位数字或者 ‘.’
题目数据 保证 输入数独仅有一个解
题解
解题思路
为了解决数独问题,我们可以使用回溯算法。这里我将给出一个更详细的Python代码实现,并包含一些优化以提高解题效率。我们将预先计算每一行、每一列和每一个3x3宫格中已有的数字,这样在尝试填充空格时就可以快速判断哪些数字是可用的。
python代码
以下是改进后的Python代码:
def solveSudoku(board):def could_place(d, row, col):"""Check if one could place a number d in (row, col) cell"""return not (d in rows[row] or d in columns[col] or d in boxes[box_index(row, col)])def place_number(d, row, col):"""Place a number d in (row, col) cell"""rows[row].add(d)columns[col].add(d)boxes[box_index(row, col)].add(d)board[row][col] = str(d)def remove_number(d, row, col):"""Remove a number which didn't lead to a solution"""rows[row].remove(d)columns[col].remove(d)boxes[box_index(row, col)].remove(d)board[row][col] = '.'def place_next_numbers(row, col):"""Call backtrack function in recursionto continue to place numberstill the moment we have a solution"""# if we're in the last column and last row, the board is completedif col == N - 1 and row == N - 1:nonlocal sudoku_solvedsudoku_solved = Trueelse:# if we're in the end of the row# go to the next rowif col == N - 1:backtrack(row + 1, 0)else:backtrack(row, col + 1)def backtrack(row=0, col=0):"""Backtracking"""if board[row][col] == '.':# iterate through all numbers from 1 to 9for d in range(1, 10):if could_place(d, row, col):place_number(d, row, col)place_next_numbers(row, col)# if sudoku is solved, there is no need to backtrack# since the single unique solution is promisedif not sudoku_solved:remove_number(d, row, col)else:place_next_numbers(row, col)# box sizen = 3# row sizeN = n * n# lambda function to compute box indexbox_index = lambda row, col: (row // n) * n + col // n# init rows, columns and boxes sets to keep track of used numbersrows = [set() for _ in range(N)]columns = [set() for _ in range(N)]boxes = [set() for _ in range(N)]for i in range(N):for j in range(N):if board[i][j] != '.':d = int(board[i][j])place_number(d, i, j)sudoku_solved = Falsebacktrack()
这段代码实现了数独求解器,其中包含了用于检查是否可以放置数字、放置数字、移除错误放置的数字以及递归地尝试填入下一个数字的辅助函数。它还预先计算了所有行、列和3x3宫格中已经出现的数字,以便更快地确定哪个数字可以放在空白处。这个版本的代码比之前提供的更加高效,因为它减少了重复的验证工作。