用python解决数独问题
时间: 2024-01-05 15:04:22 浏览: 75
数独解题python版
数独问题可以使用回溯算法来解决,可以用Python来实现这个算法。
首先,我们可以定义一个函数来检查一个数是否可以放在某一个位置上:
```python
def is_valid(board, row, col, num):
# 检查行是否合法
for i in range(9):
if board[row][i] == num:
return False
# 检查列是否合法
for i in range(9):
if board[i][col] == num:
return False
# 检查宫格是否合法
box_row = (row // 3) * 3
box_col = (col // 3) * 3
for i in range(3):
for j in range(3):
if board[box_row+i][box_col+j] == num:
return False
return True
```
然后,我们可以定义一个递归函数来解决数独问题:
```python
def solve_sudoku(board):
for i in range(9):
for j in range(9):
if board[i][j] == ".":
for num in range(1, 10):
if is_valid(board, i, j, str(num)):
board[i][j] = str(num)
if solve_sudoku(board):
return True
board[i][j] = "."
return False
return True
```
最后,我们可以使用一个示例来测试代码:
```python
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"]
]
solve_sudoku(board)
for row in board:
print(row)
```
输出结果为:
```
['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']
```
可以看到,该算法成功地解决了数独问题。
阅读全文