Contents
Figure 1: Constraint Satisfaction Problems in Python: Solve Sudoku and Scheduling — a calendar grid waiting to be filled, which is the same shape of problem as a Sudoku board once you write the rules down
A Sudoku grid and a hospital shift roster look like completely different puzzles. One uses digits, the other uses people and calendars. But both follow the same recipe: a set of variables, a set of allowed values for each, and a set of rules that the values must obey. That's a constraint satisfaction problem (CSP), and once you learn to model problems this way, a general solver does the hard work.
I can't claim I've run every snippet below, and I haven't executed the code in this conversation, so test it yourself. Sources are listed at the end rather than inline. IMO, the most valuable skill here isn't writing a solver but modeling the problem well, because the same model can feed a hand-written backtracker or an industrial engine. We'll build both. Ready?
What Is a CSP?
A project write-up built on Russell and Norvig's CSP chapter defines a CSP as a search problem with a factored state: each state is a set of variables with possible values [1]. In the simplest form, the variables have discrete, finite domains. Map coloring and scheduling with limits are the textbook examples, and course slides add graph coloring, the 8-queens puzzle, cryptarithmetic, crosswords, and design problems.
Three pieces define a CSP:
- Variables: the unknowns (81 Sudoku cells, or "which nurse covers this shift").
- Domains: each variable's allowed values (1 to 9, or a set of nurses).
- Constraints: relations the values must satisfy. A binary constraint relates two variables, and a global constraint involves an arbitrary number of them, such as "all different."
A solution assigns a value to every variable without breaking any constraint. When you also want the best solution under some objective, such as minimum schedule length, you have a constraint optimization problem (COP). The distinction matters later, because a roster with shift requests is a COP, not a plain CSP.
Modeling Sudoku as a CSP
The slides model Sudoku precisely: 81 variables (one per cell), domains {1..9}, and 27 not-equal constraints. Those 27 come from the 9 rows, 9 columns, and 9 boxes, each of which must contain distinct values. A well-posed puzzle has a unique solution, and the given digits simply shrink some domains to a single value.
Ever solved a Sudoku by crossing out candidates? You were running constraint propagation by hand. That intuition, eliminate what cannot be true, is exactly what a solver does with arithmetic.
The Three Big Ideas in CSP Solving
1. Backtracking Search
Assign a variable, check constraints, undo on failure. Naive backtracking explores huge trees, so we improve it with the two ideas that follow.
2. Inference: Propagating Constraints
Course notes call arc consistency (AC-3) virtually always used [2].
- Node consistency: every value in a variable's domain satisfies its unary constraints.
- Arc consistency: every value in a variable's domain has a compatible partner in each neighbor's domain.
- Forward checking: establishes arc consistency toward the neighbors right after the search assigns a value, which combines search and inference.
3. Ordering Heuristics
The same notes recommend picking the variable most likely to fail first, the minimum remaining values (MRV) heuristic, and the value most likely to succeed, the least constraining value. Failing early prunes whole subtrees, which is why a single ordering choice can change node counts by orders of magnitude.
Solver 1: Sudoku From Scratch
Here's a compact solver combining propagation with MRV search. It uses two rules: when a cell has one candidate left, eliminate that candidate from its peers, and when a unit has only one place left for a digit, put it there. I haven't run this, so test it:
def build():
rows = [[r * 9 + c for c in range(9)] for r in range(9)]
cols = [[r * 9 + c for r in range(9)] for c in range(9)]
boxes = [[(br * 3 + dr) * 9 + bc * 3 + dc for dr in range(3) for dc in range(3)]
for br in range(3) for bc in range(3)]
units = rows + cols + boxes
units_of = {i: [u for u in units if i in u] for i in range(81)}
peers = {i: {x for u in units_of[i] for x in u if x != i} for i in range(81)}
return units_of, peers
UNITS_OF, PEERS = build()
def eliminate(d, i, v):
if v not in d[i]:
return True
d[i].discard(v)
if not d[i]:
return False # a cell has no candidates: contradiction
if len(d[i]) == 1: # one candidate left: remove it from peers
w = next(iter(d[i]))
if not all(eliminate(d, p, w) for p in PEERS[i]):
return False
for unit in UNITS_OF[i]: # hidden single: only one cell can hold v
places = [c for c in unit if v in d[c]]
if not places:
return False
if len(places) == 1 and len(d[places[0]]) > 1:
if not assign(d, places[0], v):
return False
return True
def assign(d, i, v):
return all(eliminate(d, i, w) for w in list(d[i]) if w != v)
def parse(puzzle):
d = {i: set(range(1, 10)) for i in range(81)}
cells = [ch for ch in puzzle if ch in ".0123456789"]
for i, ch in enumerate(cells):
if ch not in ".0" and not assign(d, i, int(ch)):
return None
return d
def search(d, stats):
if d is None:
return None
if all(len(d[i]) == 1 for i in range(81)):
return d
i = min((c for c in range(81) if len(d[c]) > 1), key=lambda c: len(d[c])) # MRV
for v in sorted(d[i]):
stats["nodes"] += 1
d2 = {k: set(s) for k, s in d.items()}
if assign(d2, i, v):
result = search(d2, stats)
if result:
return result
return None
def show(d):
for r in range(9):
print(" ".join(str(next(iter(d[r * 9 + c]))) for c in range(9)))
easy = "003020600900305001001806400008102900700000008006708200002609500800203009005010300"
stats = {"nodes": 0}
solution = search(parse(easy), stats)
show(solution); print("search nodes:", stats["nodes"])
Try a harder puzzle, and watch nodes grow. Then remove the MRV line (pick the first unfilled cell instead) and compare. That single heuristic often changes node counts by orders of magnitude, which is the point of the ordering ideas above.
A subtle modeling lesson hides in the propagation. A Rust CSP library's example comment notes that its all-different constraint needed a stronger propagation than simple elimination, and that decomposing "all different" into binary not-equal constraints works for AC-3. The same library's documentation lists generalized arc consistency for all-different (Régin's algorithm) as a default option [5]. In plain English: a global constraint that "understands" the whole group prunes more than a pile of pairwise rules. Professional solvers exploit exactly that.
Solver 2: Sudoku With OR-Tools CP-SAT
Google's OR-Tools provides a production-grade constraint solver, CP-SAT. The model reads almost exactly like the problem statement. I haven't run this, and newer OR-Tools versions add snake_case method aliases, so check the docs for your version [3]:
from ortools.sat.python import cp_model
def solve_sudoku_cpsat(puzzle):
cells = [0 if ch in ".0" else int(ch) for ch in puzzle if ch in ".0123456789"]
model = cp_model.CpModel()
x = [[model.NewIntVar(1, 9, f"x{r}{c}") for c in range(9)] for r in range(9)]
for r in range(9):
model.AddAllDifferent(x[r]) # rows
for c in range(9):
model.AddAllDifferent([x[r][c] for r in range(9)]) # columns
for br in range(3):
for bc in range(3):
model.AddAllDifferent([x[br * 3 + dr][bc * 3 + dc] # boxes
for dr in range(3) for dc in range(3)])
for r in range(9):
for c in range(9):
if cells[r * 9 + c]:
model.Add(x[r][c] == cells[r * 9 + c]) # given digits
solver = cp_model.CpSolver()
status = solver.Solve(model)
if status in (cp_model.OPTIMAL, cp_model.FEASIBLE):
return [[solver.Value(x[r][c]) for c in range(9)] for r in range(9)]
return None
grid = solve_sudoku_cpsat(easy)
print(*(" ".join(map(str, row)) for row in grid), sep="\n")
Always check the solver's status. CP-SAT can return optimal, feasible, infeasible, or unknown, and "unknown" means it hit a limit without an answer. To test whether a puzzle has a unique solution, add a constraint excluding the solution you found and solve again. If that second model is infeasible, the solution is unique.
Scheduling Example 1: Nurse Rostering
Now a real-world flavor. Four nurses, seven days, three shifts per day. The rules:
- Every shift gets exactly one nurse.
- Each nurse works at most one shift per day.
- Workloads stay fair: each nurse gets between the floor and ceiling of an equal share.
- Soft preferences: satisfy as many shift requests as possible.
The first three rules are hard constraints (a CSP), and the preferences turn it into a COP with an objective. I haven't run this, so check the method names against your OR-Tools version:
def nurse_schedule(n_nurses=4, n_days=7, n_shifts=3):
model = cp_model.CpModel()
work = {(n, d, s): model.NewBoolVar(f"w{n}_{d}_{s}")
for n in range(n_nurses) for d in range(n_days) for s in range(n_shifts)}
for d in range(n_days):
for s in range(n_shifts):
model.AddExactlyOne(work[n, d, s] for n in range(n_nurses)) # shift covered once
for n in range(n_nurses):
for d in range(n_days):
model.AddAtMostOne(work[n, d, s] for s in range(n_shifts)) # one shift per day
total = n_days * n_shifts
lo, hi = total // n_nurses, -(-total // n_nurses) # floor and ceiling
for n in range(n_nurses):
count = sum(work[n, d, s] for d in range(n_days) for s in range(n_shifts))
model.Add(count >= lo)
model.Add(count <= hi)
requests = {(0, 0, 1), (1, 1, 0), (2, 2, 2), (3, 5, 0)} # (nurse, day, shift)
model.Maximize(sum(work[key] for key in requests)) # soft preferences
solver = cp_model.CpSolver()
solver.parameters.max_time_in_seconds = 10
status = solver.Solve(model)
print("status:", solver.StatusName(status))
if status in (cp_model.OPTIMAL, cp_model.FEASIBLE):
for d in range(n_days):
row = []
for s in range(n_shifts):
nurse = next(n for n in range(n_nurses) if solver.Value(work[n, d, s]))
row.append(f"S{s}:N{nurse}")
print(f"day {d}: " + " ".join(row))
nurse_schedule()
Notice the structure of the model: Boolean variables say "nurse n works shift s on day d," and constraints count them. This is the standard way to express assignment problems for CP-SAT. Now break it on purpose: raise the lower workload bound beyond what's possible, and watch the status turn infeasible. Learning to read infeasible is half the skill of constraint modeling.
Scheduling Example 2: Tasks With Precedence and Limited Workers
Scheduling often uses interval variables, which carry a start, a duration, and an end. Two global constraints do heavy lifting: NoOverlap (a machine does one thing at a time) and Cumulative (total resource use at any time stays within a capacity). The Rust library unifier, in its documentation, lists the same family of scheduling constraints (no-overlap, cumulative, and precedence) along with edge-finding propagation for no-overlap, which shows how standard these building blocks are.
Here, four tasks share two workers, and task C must wait for A and B. I haven't run this:
def project_schedule():
durations = {"A": 3, "B": 2, "C": 4, "D": 2}
precedence = [("A", "C"), ("B", "C")] # C starts after A and B finish
model = cp_model.CpModel()
horizon = sum(durations.values())
start = {t: model.NewIntVar(0, horizon, f"s_{t}") for t in durations}
iv = {t: model.NewFixedSizeIntervalVar(start[t], d, f"i_{t}") for t, d in durations.items()}
model.AddCumulative(list(iv.values()), [1] * len(iv), 2) # two workers available
for a, b in precedence:
model.Add(start[b] >= start[a] + durations[a])
makespan = model.NewIntVar(0, horizon, "makespan")
for t, d in durations.items():
model.Add(makespan >= start[t] + d)
model.Minimize(makespan)
solver = cp_model.CpSolver()
status = solver.Solve(model)
print(solver.StatusName(status), "makespan:", solver.Value(makespan))
for t in durations:
print(t, "starts at", solver.Value(start[t]))
project_schedule()
You can verify the answer by hand: A then C forms a chain of 7 time units, and the other tasks fit alongside it with two workers, so the minimum makespan should come out as 7. If your solver reports something else, hunt for a modeling bug. Checking a solver against a case you can solve mentally is the best debugging habit in this field.
Which Tool for Which Job?
- From-scratch backtracking: best for learning, and for tiny or unusual problems.
- CP-SAT (OR-Tools): best default for serious scheduling, rostering, and assignment, with global constraints and optimization.
- Dedicated CSP libraries: several exist in Python and other languages, and some document AC-3, forward checking, and MRV directly. Evaluate maintenance before adopting any.
- MIP solvers: better when the problem is mostly linear with big numeric structure (see the OR-Tools versus RL article).
- SAT and SMT solvers: better when the problem is mostly Boolean logic (the classical AI article introduced SAT).
- Local search: best when you need a good answer fast and don't need proof of optimality.
From my background knowledge, MiniZinc offers a modeling language that targets many solvers, but I haven't verified its current status here.
Modeling Tips That Save Hours
- Start tiny. Get a 2-day, 2-nurse model working before you scale.
- Add constraints one at a time, and re-solve after each, so you know which one broke feasibility.
- Test infeasibility on purpose with a case you know is impossible.
- Prefer global constraints (all-different, no-overlap, cumulative) over hand-written pairwise ones, because propagation is stronger.
- Use soft constraints sparingly. Turn hard rules into penalties only when real tradeoffs exist, and weight them thoughtfully.
- Set time limits and check status. "Feasible" isn't "optimal."
- Break symmetries, such as interchangeable nurses, to shrink the search space.
- Keep the model readable. A clear model beats a clever one.
Common Mistakes to Avoid
- Modeling with too few constraints. The solver happily returns nonsense that satisfies your incomplete rules.
- Forgetting a constraint's scope. A Sudoku with rows and columns but no boxes has many bogus solutions.
- Ignoring the status code. Don't read values from an infeasible or unknown result.
- Using huge "big-M" tricks where a global constraint would do.
- Overlooking symmetry. Equivalent solutions multiply the search effort.
- Treating soft preferences as hard and creating an infeasible roster.
- Not validating the output against the rules, independent of the solver.
- Assuming the naive backtracker scales. It won't on real scheduling problems.
Did you notice that most mistakes involve modeling, not solving? :/
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Constraint Processing | a rigorous treatment of backtracking, forward checking, arc consistency, and the trade-offs between them, written by one of the researchers who shaped the field. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read it after your Sudoku solver already works. The chapters on variable ordering and consistency propagation land much harder once you have watched the node count drop on your own grid.
Wrapping Up
A CSP is variables, domains, and constraints; solvers combine search with propagation, and good ordering heuristics decide whether a problem takes milliseconds or hours. You built a Sudoku solver from scratch to see the machinery, then let CP-SAT handle Sudoku, nurse rostering, and task scheduling with a much more declarative style. The transferable skill is modeling: spell out the rules precisely, and let the engine search.
So run the from-scratch solver on the easy and hard puzzles this week and compare node counts with and without MRV. Then take one real scheduling headache from your own work and write down its variables, domains, and rules before touching code. If the model fits on half a page, you're ready for CP-SAT. If it doesn't, congratulations: you just found the ambiguity that would have haunted your schedule in production. :)
Frequently Asked Questions
What is a constraint satisfaction problem?
A CSP is defined by variables, a finite domain of allowed values for each variable, and constraints that the values must satisfy. A solution assigns every variable a value from its domain without breaking any rule. Sudoku, map coloring, nurse rostering and timetabling are all CSPs underneath.
What is the difference between a CSP and a COP?
A CSP asks for any assignment that satisfies the constraints. A constraint optimization problem, or COP, adds an objective and asks for the best satisfying assignment, such as the shortest schedule or the roster that fulfills the most shift requests. Every COP is a CSP with an extra preference to maximize or minimize.
Why use OR-Tools CP-SAT instead of a hand-written solver?
CP-SAT gives you production-grade propagation, global constraints such as all-different, no-overlap and cumulative, plus optimization and symmetry breaking out of the box. A hand-written backtracker is better for learning the machinery, but it will not scale to real rostering problems the way a mature solver does.
What does an unknown solver status mean?
When CP-SAT returns unknown, it hit a time or search limit without proving optimality or infeasibility. The status is not a result. You must check for feasible or optimal before reading variable values, and treat unknown as a prompt to raise the limit or simplify the model.
How do I know a Sudoku puzzle has a unique solution?
Solve it once, then add a constraint that excludes the solution you found and solve again. If the second model is infeasible, the solution is unique. If it finds another grid, the puzzle has multiple solutions and is not well posed. This exclusion trick works in any constraint solver.
Sources
[1]Russell and Norvig, Artificial Intelligence: A Modern Approach (4th edition) - the CSP chapter on factored states, binary and global constraints, backtracking search, MRV, and forward checking: aima.cs.berkeley.edu[2]Rina Dechter, Constraint Processing (2003) - node, arc and path consistency, propagation, and the cost trade-offs that motivate them: elsevier.com[3]Google OR-Tools, CP-SAT solver documentation - integer variables, all-different, no-overlap, cumulative, objectives and status codes: developers.google.com[4]Peter Norvig, Solving Every Sudoku Puzzle - constraint propagation plus search on a 9x9 grid, and the standard easy-puzzle test string: norvig.com[5]Jean-Charles Régin, A Filtering Algorithm for Constraints of Difference in CSPs (1994) - the generalized arc consistency algorithm for all-different constraints: aaai.org
