← Blog

Constraint Satisfaction Problems: Map and Rota Examples

By Umar Shakar · 15 Nov 2026 · Artificial Intelligence

On this page

Some problems are not about finding a route. They are about filling in blanks so that a list of rules is never broken. Who works which shift. Which room each exam goes in. Which colour each region gets on a map. In AI these are called constraint satisfaction problems, or CSPs, and they show up in real software far more often than people realise.

I first ran into one properly when a client asked for a booking form that would not let two appointments overlap and would not give the same staff member back-to-back late shifts. A pile of if statements got messy fast. Treating it as a CSP made the logic short and easy to change. This guide explains how CSPs work, using two original examples and a small Python solver.

The situation: many choices, many rules

Picture a small café that opens Friday to Sunday with a morning and an evening shift each day. Three people can cover them. One has a class on Saturday morning, another leaves early on Sunday, and nobody should work both shifts on the same day. With six shifts and three people there are 36 = 729 possible rotas. That is small enough to brute force, but add a few more staff and a full week and the number runs into the billions. You need a smarter way to search.

What is a constraint satisfaction problem?

A CSP has three parts:

A solution is a value for every variable that breaks no constraint. Most constraints in everyday problems are binary, meaning they link two variables. Some are global, such as "everyone must work at least one shift", which involves all variables at once.

The value of this framing is that one general solver can handle very different problems. You only change the variables, domains and constraints. The textbook treatment in Russell and Norvig's Artificial Intelligence: A Modern Approach covers the methods below in more depth.

Backtracking is the workhorse. It picks a variable, tries a value, and moves on to the next variable. As soon as a choice breaks a constraint, it undoes the most recent choice and tries the next value. It is a depth-first search that refuses to continue down a path that is already broken.

Forward checking

Plain backtracking only notices a problem when it reaches the variable that clashes. Forward checking looks ahead. Each time a value is assigned, it removes now-impossible values from the domains of the neighbouring variables. If any domain becomes empty, the solver knows immediately that this choice is a dead end and backtracks without wasting more time.

Arc consistency and AC-3

Arc consistency goes further than forward checking. An "arc" from X to Y is consistent if every value left in X has at least one compatible value in Y. The AC-3 algorithm, introduced by Alan Mackworth (Mackworth, 1977), keeps a queue of arcs and removes unsupported values until nothing changes. When a value is removed from X, every arc pointing into X goes back on the queue, because its neighbours might have lost their support. AC-3 can be run once before search, or after each assignment.

MRV and degree heuristics

The order in which you fill in variables matters a lot. The minimum remaining values (MRV) heuristic picks the variable with the fewest legal values left. The idea is "fail first": if a variable is going to cause trouble, find out now. When several variables tie, the degree heuristic breaks the tie by choosing the variable involved in the most constraints with unassigned variables. For choosing which value to try first, a common partner is the least constraining value heuristic, which prefers the value that rules out the fewest options for neighbours.

Example 1: colouring a made-up island map

The map colouring problem asks you to colour regions so that no two neighbours share a colour. I invented a small island with six regions so the example is entirely original:

Each region is a variable, each domain is {Red, Green, Blue}, and every shared border is a "must be different" constraint.

Watch how much work the inference does. Suppose we set Harbour to Red and Old Town to Green. Forward checking leaves Dunes with only {Blue}, because it touches both. Now run AC-3: Dunes being Blue forces Marina to Green and Oasis to Red. Oasis being Red forces Hills to Blue. The whole map is solved with no further guessing. This is why arc consistency is so useful: on tightly linked problems it can do most of the search for you.

Old Town and Dunes each have four neighbours, so the degree heuristic would choose one of them first. In a real map tool that ordering matters much more than on six regions.

Example 2: a weekend café rota

Back to the café. The variables are Fri AM, Fri PM, Sat AM, Sat PM, Sun AM and Sun PM. Aisha, Ben and Carlos can each work any shift, with two exceptions: Aisha cannot do Saturday morning and Ben cannot do Sunday evening. The binary constraint is that the two shifts on the same day must go to different people.

MRV kicks in straight away. Sat AM and Sun PM only have two candidates each, so the solver fills those first, before the easy shifts.

Python backtracking code with MRV and forward checking

The solver below is generic. It takes a list of variables, a dictionary of domains, and a function that says whether two assignments are compatible. If you need a refresher on the dictionary syntax, see my guide to Python lists and dictionaries.

def solve(variables, domains, ok, assignment=None):
    """Backtracking with MRV and forward checking."""
    if assignment is None:
        assignment = {}
    if len(assignment) == len(variables):
        return assignment
    # MRV: pick the unassigned variable with the fewest values left
    var = min((v for v in variables if v not in assignment),
              key=lambda v: len(domains[v]))
    for value in domains[var]:
        assignment[var] = value
        # Forward checking: trim the domains of the other unassigned variables
        pruned = {v: [x for x in domains[v] if ok(var, value, v, x)]
                  for v in variables if v not in assignment}
        if all(pruned.values()):              # no domain was wiped out
            result = solve(variables, {**domains, **pruned}, ok, assignment)
            if result:
                return result
        del assignment[var]
    return None

# 1) Map colouring: a made-up island with six regions
borders = {
    "Harbour":   ["Old Town", "Dunes", "Marina"],
    "Old Town":  ["Harbour", "Dunes", "Hills", "Oasis"],
    "Dunes":     ["Harbour", "Old Town", "Oasis", "Marina"],
    "Hills":     ["Old Town", "Oasis"],
    "Oasis":     ["Old Town", "Dunes", "Hills"],
    "Marina":    ["Harbour", "Dunes"],
}
regions = list(borders)
colours = {r: ["Red", "Green", "Blue"] for r in regions}

def different_if_neighbours(a, va, b, vb):
    return not (b in borders[a] and va == vb)

print(solve(regions, colours, different_if_neighbours))

# 2) Weekend shift rota for a small cafe
shifts = ["Fri AM", "Fri PM", "Sat AM", "Sat PM", "Sun AM", "Sun PM"]
staff = {s: ["Aisha", "Ben", "Carlos"] for s in shifts}
staff["Sat AM"] = ["Ben", "Carlos"]           # Aisha has a class on Saturday morning
staff["Sun PM"] = ["Aisha", "Carlos"]         # Ben leaves early on Sunday

def same_day(a, b):
    return a.split()[0] == b.split()[0]

def rota_rule(a, pa, b, pb):
    return not (same_day(a, b) and pa == pb)  # nobody works a double on one day

print(solve(shifts, staff, rota_rule))

Expected output:

{'Harbour': 'Red', 'Old Town': 'Green', 'Dunes': 'Blue', 'Oasis': 'Red', 'Hills': 'Blue', 'Marina': 'Green'}
{'Sat AM': 'Ben', 'Sat PM': 'Aisha', 'Sun PM': 'Aisha', 'Sun AM': 'Ben', 'Fri AM': 'Aisha', 'Fri PM': 'Ben'}

The map result matches the hand trace above. The rota result is valid, but look closely: Aisha works three shifts and Carlos works none. Nothing in our rules said otherwise. This is the most common lesson with CSPs. The solver does exactly what the constraints say, so fairness has to be written down as a constraint too, for example a global rule such as "each person works between one and three shifts". Adding that kind of rule needs a solver that supports global constraints, or a small extra check inside the search.

Tips for modelling real CSPs

Comparison of CSP techniques

TechniqueWhat it doesMain benefit
BacktrackingAssigns one variable at a time and undoes bad choicesSimple and complete
Forward checkingPrunes neighbours' domains after each assignmentSpots dead ends one step early
AC-3Enforces arc consistency across the whole networkRemoves many impossible values before guessing
MRVChooses the most constrained variable nextFails fast, smaller search tree
Degree heuristicBreaks MRV ties by number of constraintsGood first choice on large maps

Key takeaways

Frequently asked questions

What are some common constraint satisfaction problem examples?

Map colouring, Sudoku, staff rotas, exam timetabling, seating plans and assigning delivery slots are all CSPs. Each one fills in a set of choices that must follow a list of rules.

How many colours do you need for the map colouring problem?

For any map drawn on a flat surface, four colours are always enough, a result known as the four colour theorem. Many small maps, like the island in this guide, can be done with three.

What is the difference between forward checking and arc consistency?

Forward checking only checks the direct neighbours of the variable you just assigned. Arc consistency keeps checking every pair of linked variables until no more values can be removed, so it catches problems further away.

Is backtracking search always slow?

In the worst case it can be, because the number of combinations grows exponentially. In practice, good heuristics and inference make it fast enough for many real scheduling problems.

If your website needs a booking system, rota tool or any form with tricky business rules, see my web development and SEO services. New to Python? My introduction to Python is the place to start.

Need a website, SEO or a custom business app?
I'm Umar, a web developer and SEO specialist in Abu Dhabi. Get in touch.