回溯法生活中应用代码举例
时间: 2023-08-16 18:09:22 浏览: 97
下面是一个生活中应用回溯法的示例代码:解数独问题。
数独是一种数学智力游戏,玩家需要在 9x9 的网格中填入数字,使得每一行、每一列和每一个 3x3 的宫(共 9 个)内的数字都是 1~9 的不同数字。如果你遇到了数独难题,可以使用回溯算法来解决。
下面是使用回溯算法解决数独问题的示例代码:
```python
def solve_sudoku(board):
"""
解数独问题
:param board: 数独题目,是一个 9x9 的二维数组
:return: 如果存在解,则返回解,否则返回 None
"""
def backtrack(board, row, col):
if col == 9:
# 进入下一行
return backtrack(board, row + 1, 0)
if row == 9:
# 找到解
return True
if board[row][col] != '.':
# 当前位置已经有数字,跳过
return backtrack(board, row, col + 1)
for num in range(1, 10):
if not is_valid(board, row, col, str(num)):
continue
board[row][col] = str(num)
if backtrack(board, row, col + 1):
return True
board[row][col] = '.'
return False
def is_valid(board, row, col, num):
for i in range(9):
if board[row][i] != '.' and board[row][i] == num:
return False
if board[i][col] != '.' and board[i][col] == num:
return False
if board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] != '.' and board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == num:
return False
return True
if backtrack(board, 0, 0):
return board
else:
return None
```
使用方法:
```python
board = [
["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"]
]
solution = solve_sudoku(board)
if solution:
for row in solution:
print(row)
else:
print("No solution")
```
输出:
```
['5', '3', '4', '6', '7', '8', '9', '1', '2']
['6', '7', '2', '1', '9', '5', '3', '4', '8']
['1', '9', '8', '3', '4', '2', '5', '6', '7']
['8', '5', '9', '7', '6', '1', '4', '2', '3']
['4', '2', '6', '8', '5', '3', '7', '9', '1']
['7', '1', '3', '9', '2', '4', '8', '5', '6']
['9', '6', '1', '5', '3', '7', '2', '8', '4']
['2', '8', '7', '4', '1', '9', '6', '3', '5']
['3', '4', '5', '2', '8', '6', '1', '7', '9']
```
阅读全文