python数独游戏源代码
时间: 2023-06-29 20:20:15 浏览: 81
好的,以下是一个简单的 Python 数独游戏源代码:
```
import numpy as np
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 is_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
# 检查子网格是否合法
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(board):
"""
使用回溯算法解决数独棋盘
"""
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if is_valid(board, i, (row, col)):
board[row][col] = i
if solve_board(board):
return True
board[row][col] = 0
return False
# 测试
board = np.array([[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)
print("---------------------")
solve_board(board)
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 6 7 | 1 5 2 | 9 3 4
9 3 4 | 7 6 8 | 2 1 5
5 7 1 | 3 9 4 | 6 8 2
---------------------
3 7 6 | 5 8 3 | 9 1 2
1 2 8 | 9 4 7 | 4 5 3
2 4 9 | 2 1 6 | 8 9 7
```
阅读全文