or-tools cp-sat CpModel.AddAllDifferent
- 1 示例程序
1 示例程序
链接: 官方文档
from ortools.sat.python import cp_modeldef sudoku_solver(puzzle):# 创建一个 CP-SAT 模型model = cp_model.CpModel()# 创建变量board = [[model.NewIntVar(1, 9, f'cell_{i}_{j}') for j in range(9)] for i in range(9)]# 添加行约束:每一行中的数字互不相同for i in range(9):model.AddAllDifferent(board[i])# 添加列约束:每一列中的数字互不相同for j in range(9):model.AddAllDifferent([board[i][j] for i in range(9)])# 添加九宫格约束:每一个3x3小九宫格中的数字互不相同for i in range(0, 9, 3):for j in range(0, 9, 3):model.AddAllDifferent([board[i+r][j+c] for r in range(3) for c in range(3)])# 添加初始已知数字的约束for i in range(9):for j in range(9):if puzzle[i][j] != 0:model.Add(board[i][j] == puzzle[i][j])# 创建求解器solver = cp_model.CpSolver()# 解决问题status = solver.Solve(model)# 打印解if status == cp_model.FEASIBLE:print("找到解:")for i in range(9):row = [solver.Value(board[i][j]) for j in range(9)]print(row)else:print("未找到解.")# 示例数独题目
sudoku_puzzle = [[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]
]# 解决数独问题
sudoku_solver(sudoku_puzzle)