Files
ortools-clone/examples/python/sudoku_sat.py

80 lines
2.3 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
2025-01-10 11:35:44 +01:00
# Copyright 2010-2025 Google LLC
2010-09-15 12:42:33 +00:00
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
2010-09-15 12:42:33 +00:00
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
2023-07-01 06:06:53 +02:00
2010-09-15 12:42:33 +00:00
"""This model implements a sudoku solver."""
2018-11-19 18:04:52 -08:00
from ortools.sat.python import cp_model
2018-06-11 11:51:18 +02:00
2018-11-19 18:04:52 -08:00
def solve_sudoku() -> None:
2018-11-21 11:00:26 -08:00
"""Solves the sudoku problem with the CP-SAT solver."""
2018-11-19 18:04:52 -08:00
# Create the model.
model = cp_model.CpModel()
2010-09-15 12:42:33 +00:00
cell_size = 3
line_size = cell_size**2
line = list(range(0, line_size))
cell = list(range(0, cell_size))
2010-09-15 12:42:33 +00:00
2023-07-01 06:06:53 +02:00
initial_grid = [
[0, 6, 0, 0, 5, 0, 0, 2, 0],
[0, 0, 0, 3, 0, 0, 0, 9, 0],
[7, 0, 0, 6, 0, 0, 0, 1, 0],
[0, 0, 6, 0, 3, 0, 4, 0, 0],
[0, 0, 4, 0, 7, 0, 1, 0, 0],
[0, 0, 5, 0, 9, 0, 8, 0, 0],
[0, 4, 0, 0, 0, 1, 0, 0, 6],
[0, 3, 0, 0, 0, 8, 0, 0, 0],
[0, 2, 0, 0, 4, 0, 0, 5, 0],
]
2010-09-15 12:42:33 +00:00
grid = {}
for i in line:
for j in line:
2023-11-16 19:46:56 +01:00
grid[(i, j)] = model.new_int_var(1, line_size, "grid %i %i" % (i, j))
2010-09-15 12:42:33 +00:00
# AllDifferent on rows.
for i in line:
2023-11-16 19:46:56 +01:00
model.add_all_different(grid[(i, j)] for j in line)
2010-09-15 12:42:33 +00:00
# AllDifferent on columns.
2010-09-15 12:42:33 +00:00
for j in line:
2023-11-16 19:46:56 +01:00
model.add_all_different(grid[(i, j)] for i in line)
# AllDifferent on cells.
for i in cell:
for j in cell:
one_cell = []
for di in cell:
for dj in cell:
2023-07-01 06:06:53 +02:00
one_cell.append(grid[(i * cell_size + di, j * cell_size + dj)])
2010-09-15 12:42:33 +00:00
2023-11-16 19:46:56 +01:00
model.add_all_different(one_cell)
2010-09-15 12:42:33 +00:00
# Initial values.
for i in line:
for j in line:
if initial_grid[i][j]:
2023-11-16 19:46:56 +01:00
model.add(grid[(i, j)] == initial_grid[i][j])
2023-11-16 19:46:56 +01:00
# Solves and prints out the solution.
2018-11-19 18:04:52 -08:00
solver = cp_model.CpSolver()
2023-11-16 19:46:56 +01:00
status = solver.solve(model)
if status == cp_model.OPTIMAL:
for i in line:
2023-11-16 19:46:56 +01:00
print([int(solver.value(grid[(i, j)])) for j in line])
2010-09-15 12:42:33 +00:00
2018-11-19 18:04:52 -08:00
solve_sudoku()