数独游戏python代码
时间: 2023-02-22 18:30:35 浏览: 58
数独游戏的 Python 代码可以用多种方式实现。下面是一个简单的示例:
```
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
def solve(board):
for row in range(9):
for col in range(9):
if board[row][col] == 0:
for num in range(1, 10):
if is_valid(board, row, col, num):
board[row][col] = num
if solve(board):
return True
board[row][col] = 0
return False
return True
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] == num or board[i][col] == num:
return False
row_start = (row//3) * 3
col_start = (col//3) * 3
for i in range(3):
for j in range(3):
if board[row_start+i][col_start+j] == num:
return False
return True
if solve(board):
for row in board:
print(row)
else:
print("No solution found")
```
这是一个使用回溯算法的简单数独求解程序。
阅读全文