Constraint satisfaction
A constraint satisfaction problem (CSP) asks for a value for each variable such that every required condition holds. The variables describe decisions, domains list allowed values, and constraints rule out incompatible combinations. For example, two jobs scheduled in the same time slot must use different rooms. No training data or language model is needed: the desired answer can be checked directly against the rules.
Represent a scheduling problem
A fictional studio has two jobs, paint and pack, both needing a room at 10:00. Each can use red or blue. Variables are the two job names. Both domains are [red, blue]. The binary constraint is paint ≠ pack. Assigning paint=red and pack=blue works, as does the reverse. Assigning both red violates the constraint. A unary constraint restricts one variable (e.g. paint must use red); in this example encode it by reducing that domain. A general CSP may have constraints on more than two variables; this lesson only solves pairwise inequality.
Check a complete solution independently
The checker requires exactly the declared jobs, checks room membership, then compares each conflicting pair. Missing jobs, extra jobs and illegal rooms are rejected even if the conflicts happen to pass. The input contract is a dictionary of string job names to lists of unique string room names, a list of pairs of declared job names, and a candidate dictionary. An empty problem has the valid empty assignment. A self-conflict cannot be satisfied. These functions assume valid problem definitions; malformed conflict endpoints are outside scope.
def valid_schedule(domains, conflicts, assignment): if set(assignment) != set(domains): return False if any(assignment[job] not in domains[job] for job in domains): return False return all(assignment[a] != assignment[b] for a, b in conflicts)
domains = {"paint": ["red", "blue"], "pack": ["red", "blue"]}conflicts = [("paint", "pack")]print(valid_schedule(domains, conflicts, {"paint": "red", "pack": "blue"}))print(valid_schedule(domains, conflicts, {"paint": "red", "pack": "red"}))The first result is True because both jobs have permitted, different rooms. The second is False because the conflict is violated. There is no requirement to pick one canonical valid assignment. A checker is often much cheaper than a solver: it evaluates an existing answer, rather than exploring many candidates.
Search with backtracking and forward checking
A simple exhaustive approach tries every complete combination. With n variables and at most d choices each there can be d^n combinations. Backtracking assigns one variable at a time and abandons partial assignments that cannot lead to a solution. Forward checking removes a chosen room from the domains of its unassigned conflicting neighbors. If any domain becomes empty, the current choice cannot succeed. It does not check all relationships among unassigned neighbors, so a nonempty set of domains is not proof that a solution exists.
The minimum remaining values (MRV) heuristic chooses the job with the smallest remaining domain. If two jobs tie, this implementation selects the alphabetically earlier name; rooms are tried in input order. Branches copy domain lists, so a failed choice cannot accidentally remove a room from a later alternative. The recursion stops when every job has a value. It returns None only after exhausting alternatives; an empty dictionary is a valid assignment, not failure.
def solve_schedule(domains, conflicts): neighbors = {job: set() for job in domains} for a, b in conflicts: if a == b: return None neighbors[a].add(b) neighbors[b].add(a)
def search(assigned, remaining): if not remaining: return assigned job = min(remaining, key=lambda j: (len(remaining[j]), j)) for room in remaining[job]: # Each branch owns its own remaining domains. next_domains = {j: list(rooms) for j, rooms in remaining.items() if j != job} for other in neighbors[job] & next_domains.keys(): next_domains[other] = [r for r in next_domains[other] if r != room] if any(not rooms for rooms in next_domains.values()): continue answer = search({**assigned, job: room}, next_domains) if answer is not None: return answer return None
return search({}, {j: list(rooms) for j, rooms in domains.items()})
domains = {"paint": ["red", "blue"], "pack": ["red", "blue"]}conflicts = [("paint", "pack")]print(solve_schedule(domains, conflicts))print(solve_schedule({"paint": ["red"], "pack": ["red"]}, conflicts))Output: the first line is {'pack': 'red', 'paint': 'blue'} and the next line is None. Pack is selected first by the tie rule. Its red choice removes red from paint. In the second problem both jobs have only red; picking either makes the other domain empty. To see backtracking, try a chain of conflicts with three jobs and a restricted last domain. The solver may discard a first choice and later succeed. Validate any returned assignment with valid_schedule rather than comparing a string representation.
Feasibility, optimization and common mistakes
Feasibility means all hard constraints hold. Optimization additionally compares feasible answers by an objective, such as total room cost. MRV may reduce search but does not guarantee a polynomial runtime or a cheapest schedule. Forward checking is weaker than full constraint propagation; it does not make search unnecessary. An ordinary constraint solver is a good choice when the constraints are explicit and verifiable. Large problems require bounded execution, tested libraries, and explicit outcomes for timeouts rather than treating a timeout as proof of unsatisfiability.
Practice and next step
Use the checker to evaluate both valid room assignments, then add a third job conflicting with both existing jobs while keeping only two rooms. Predict whether a schedule exists before running the solver. Try assigning the third job a new room and check the result. Next, extend the idea of valid decisions to an ordered sequence of actions whose effects change the state.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constraint satisfaction — understanding check
Apply the chapter concepts to new situations.
Which item is a domain in the studio example?
Both paint and pack must be assigned a room. Their only permitted room is red, and they must use different rooms. What is true?
After assigning pack=red, how does forward checking update an unassigned conflicting job with domain [red, blue]?
Three jobs each have domain [red, blue], and every pair of jobs must use different rooms. What does this example demonstrate?
If solve_schedule returns an assignment rather than None, what does the result guarantee under the stated input contract?