数独算法代码python
时间: 2023-05-15 14:03:03 浏览: 296
数独游戏可以通过编写算法来自动解决。Python是一种流行的编程语言,常用于编写算法。下面是一个简单的数独算法代码示例,用Python编写:
```
def solve_sudoku(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_sudoku(board):
return True
board[row][col] = 0
return False
def valid(board, num, pos):
# Check row
for i in range(len(board[0])):
if board[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(board)):
if board[i][pos[1]] == num and pos[0] != i:
return False
# Check 3x3 box
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 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
board = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
]
# Update the board with valid numbers
board = [
[0,2,3,0,0,0,0,8,0],
[0,0,0,7,0,0,0,0,1],
[6,0,0,0,0,2,0,0,0],
[0,3,0,0,0,0,5,0,7],
[0,0,9,0,2,0,6,3,0],
[0,7,0,0,0,0,9,4,2],
[7,0,0,0,0,9,0,0,0],
[0,0,0,0,0,3,0,0,0],
[2,0,1,0,0,0,0,6,0]
]
print_board(board)
solve_sudoku(board)
print("\nSolved Board:")
print_board(board)
```
这个算法的实现递归调用`find_empty`函数来查找空的格子,然后使用`valid`函数判断这个格子是否可以填写数字,如果可以则填写数字并通过递归调用进行下一步验证,如果无法填写,则返回上一个步骤继续寻找其他可行解。这个算法非常直接简单,适合初学者练习编写算法。
需要注意的是,这个算法并不一定可以解决所有的数独问题,有一些特定类型的问题可能无法解决。因此,如果您需要解决复杂的数独问题,请参考更复杂、更完整的算法实现。
阅读全文