编写一段python代码,使其利用DFS算法解决八数码问题
时间: 2024-10-08 21:11:53 浏览: 49
在Python中,我们可以使用深度优先搜索(Depth First Search,简称DFS)来解决经典的八数码问题(也称为数独)。以下是使用递归实现DFS的一个简单示例:
```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_x = (row // 3) * 3
box_y = (col // 3) * 3
# 检查九宫格
for i in range(box_x, box_x + 3):
for j in range(box_y, box_y + 3):
if board[i][j] == num:
return False
return True
def solve_sudoku(board):
def dfs(row, col):
nonlocal solved
if row == 9:
solved = True
return True
for num in range(1, 10):
if is_valid(board, row, col, num):
board[row][col] = num
# 继续处理下一行或列的下一个数字
if dfs(row + 1, col) or dfs(row, col + 1):
return True
# 如果回溯到这里,说明尝试这个位置失败了,恢复并继续寻找其他可能
board[row][col] = 0
return False
solved = False
dfs(0, 0)
return solved, board if solved else None
# 示例:解决一个数独谜题
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]
]
solved, result_board = solve_sudoku(board)
if solved:
print("Sudoku solved!")
else:
print("No solution exists.")
阅读全文