Question: my output keeps getting No optimal solution but it has one and I need it to solve my sudoku puzzle here's my code to

my output keeps getting "No optimal solution" but it has one and I need it to solve my sudoku puzzle here's my code to help fix:
import pyomo.environ as pyo
# Define the model and grid parameters
model = pyo.ConcreteModel()
N =9 # Grid size for standard Sudoku
values_range = range(1, N +1)
rows_range = range(N)
cols_range = range(N)
# Decision variable: x[r, c, n] is 1 if number n is in cell (r, c),0 otherwise
model.x = pyo.Var(rows_range, cols_range, values_range, domain=pyo.Binary)
model.constraints = pyo.ConstraintList()
# Constraint 1: Each cell contains one number
for r in rows_range:
for c in cols_range:
model.constraints.add(sum(model.x[r, c, n] for n in values_range)==1)
# Constraint 2: Each row contains unique values
for r in rows_range:
for n in values_range:
model.constraints.add(sum(model.x[r, c, n] for c in cols_range)==1)
# Constraint 3: Each column contains unique values
for c in cols_range:
for n in values_range:
model.constraints.add(sum(model.x[r, c, n] for r in rows_range)==1)
# Constraint 4: Each 3x3 block contains unique values
sqrtN =3
for br in range(0, N, sqrtN):
for bc in range(0, N, sqrtN):
for n in values_range:
model.constraints.add(
sum(model.x[r, c, n] for r in range(br, br + sqrtN) for c in range(bc, bc + sqrtN))==1
)
# Constraint 5: Pre-filled values
prefilled_cells ={
(0,0,8),
(1,2,3),(1,3,6),
(2,1,7),(2,4,9),(2,6,2),
(3,0,5),(3,5,7),
(4,4,4),(4,5,5),(4,6,7),
(5,3,1),(5,7,3),
(6,3,1),(6,7,6),(6,8,8),
(7,2,8),(7,3,5),(7,7,1),
(8,1,9),(8,6,4)
}
for (r, c, n) in prefilled_cells:
model.constraints.add(model.x[r, c, n]==1)
# Solve the model
result = pyo.SolverFactory("glpk").solve(model)
# Print results
if result.solver.termination_condition == pyo.TerminationCondition.optimal:
print("Solved Sudoku Puzzle:")
for r in rows_range:
row =[]
for c in cols_range:
for n in values_range:
if model.x[r, c, n]==1:
row.append(n)
break
print("".join(str(num) for num in row))
else:
print("No optimal solution found.")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!