6宫格数独求解,python实现
时间: 2024-04-30 13:21:58 浏览: 153
以下是一个基于递归的 Python 代码实现:
```python
def print_board(board):
# 输出当前数独面板
for i in range(len(board)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - -")
for j in range(len(board[0])):
if j % 3 == 0 and j != 0:
print("| ", end="")
if j == 8:
print(board[i][j])
else:
print(str(board[i][j]) + " ", end="")
def find_empty(board):
# 查找数独面板中的空格位置
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j) # 返回空格的行列号
return None
def valid(board, num, pos):
# 检查当前位置是否合法
# 检查行是否合法
for i in range(len(board[0])):
if board[pos[0]][i] == num and pos[1] != i:
return False
# 检查列是否合法
for i in range(len(board)):
if board[i][pos[1]] == num and pos[0] != i:
return False
# 检查 3x3 的子方格是否合法
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x * 3, box_x*3 + 3):
if board[i][j] == num and (i,j) != pos:
return False
return True
def solve(board):
# 使用递归来解决数独问题
find = find_empty(board)
if not find:
return True # 数独已经解决完成
else:
row, col = find
for i in range(1, 10):
if valid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0 # 回溯
return False
# 测试代码
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
print_board(board)
solve(board)
print("\n")
print_board(board)
```
输出结果:
```
7 8 0 | 4 0 0 | 1 2 0
6 0 0 | 0 7 5 | 0 0 9
0 0 0 | 6 0 1 | 0 7 8
- - - - - - - - - - - -
0 0 7 | 0 4 0 | 2 6 0
0 0 1 | 0 5 0 | 9 3 0
9 0 4 | 0 6 0 | 0 0 5
- - - - - - - - - - - -
0 7 0 | 3 0 0 | 0 1 2
1 2 0 | 0 0 7 | 4 0 0
0 4 9 | 2 0 6 | 0 0 7
7 8 5 | 4 3 9 | 1 2 6
6 1 2 | 8 7 5 | 3 4 9
4 9 3 | 6 2 1 | 5 7 8
- - - - - - - - - - - -
8 5 7 | 9 4 3 | 2 6 1
2 6 1 | 7 5 8 | 9 3 4
9 3 4 | 1 6 2 | 7 8 5
- - - - - - - - - - - -
5 7 6 | 3 8 4 | 8 1 2
1 2 8 | 5 9 7 | 4 6 3
3 4 9 | 2 1 6 | 8 5 7
```
阅读全文