AlgoTales · Roadmap

Constraint satisfaction

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Constraint satisfaction is the general problem of giving values to items so that a list of rules is never broken, such as colouring a map so neighbours differ. You assign one item at a time, check the rules, and step back on a clash. Many real scheduling features are this problem in disguise.

Practical use cases

  • Web app: Hospital duty roster generator. A clinic portal creates a weekly roster where nobody works two nights in a row, every shift has a senior doctor, and leave requests are honoured. The code assigns one shift at a time and backs up when a rule is broken. The manager gets a valid roster rather than a spreadsheet of clashes.
  • Web app: College timetable builder. A school admin screen has a Generate Timetable button. Each class-period needs a teacher and room with no double-booking. Assigning one slot at a time and retreating on clashes produces a working timetable in seconds, instead of days of manual fixing. When a teacher goes on leave, the admin presses the button again and a fresh clash-free timetable appears, instead of someone spending an afternoon moving lessons around.
  • System: Radio frequencies and compilers. Phone towers close to each other cannot share a frequency, which is map colouring in a different outfit. Compilers also use colouring ideas to assign CPU registers to variables. In each of these systems the engine assigns, checks the rules, and retreats on a clash, only on a far larger scale than a school timetable.

The story: Painting the Mohalla Map

For the Republic Day parade, the children of the mohalla had to paint a big map of five lanes on the school wall. Mrs. Sharma had one rule: "Lanes that touch must have different colours, so the borders stay clear." The paint pots held red, green and blue.

Aarav painted lane A red, lane B red (they did not touch, so fine), and then lane C green. Lane D touched A and C, so blue was the only colour left. Then lane E arrived: it touched B (red), C (green) and D (blue). No colour left! Aarav stared at the wall.

"Don't paint over everything," said Mrs. Sharma. "Go back and repaint the last lane you changed, then try again." Aarav tried a new colour for D, then for C, even for B, until finally lane E found a colour that fit. The map was done with a few repainted lanes.

What Aarav followed is a constraint satisfaction problem: a set of variables (lanes), a list of choices for each (colours), and rules that say which pairs clash. The method is backtracking: assign one variable, check the rules, and undo when stuck. Sudoku and N-Queens are the same idea in different costumes.

How to spot this problem, and where you need it

You have a set of things to assign, like slots, colours or people, and a list of rules that forbid certain combinations. Doing it by hand keeps causing clashes.

Signs you need it

  • The requirements read like "A and B must not be together", "each person at most once a day" or "neighbours must differ".
  • Fixing one clash creates another elsewhere, so manual changes go in circles.
  • The raw number of possible assignments is enormous, but most partial assignments obviously break a rule.

Where to use it in a project

  • Generating rosters, timetables, exam schedules and room allocations.
  • Assigning colours, frequencies or categories where neighbours must differ.

The solution

List the items to assign and the allowed values for each. Take the next item and try each allowed value. Check it against the rules with items already assigned. If it passes, move on to the next item; if it breaks a rule, try the next value. If no value works, go back and change the previous item. Picking the most restricted item first makes dead ends show up sooner and saves effort.

Payoff: Before: hours of manual roster fixing. After: a valid weekly roster in under a second, regenerated whenever leave changes.

Explain it like I am 8

You have to colour a map so touching areas never match. Colour one area at a time, checking its neighbours. If you reach an area where every colour clashes, you made a bad choice earlier. Rub out the last colour you used and try another one.

How it works, step by step

  1. Name the three parts: variables (things to decide), domains (allowed values for each), and constraints (rules between them).
  2. Pick the next unassigned variable (here the next area in order).
  3. For each value in its domain, check the constraints against the variables already assigned. Skip values that clash.
  4. Choose a good value, then explore the next variable.
  5. Un-choose if the rest fails, and try the next value.
  6. If a variable has no valid value, return failure. If every variable is assigned, we have a solution.

The code in four languages

PHP

<?php
// Colour areas so that no two neighbouring areas share a colour (backtracking CSP).
function colourMap(array $areas, array $edges, array $colours): ?array {
    $neighbours = [];
    foreach ($edges as [$a, $b]) {
        $neighbours[$a][] = $b;
        $neighbours[$b][] = $a;
    }
    $assigned = [];
    $solve = function (int $i) use (&$solve, &$assigned, $areas, $neighbours, $colours): bool {
        if ($i === count($areas)) return true;               // every variable assigned
        $area = $areas[$i];
        foreach ($colours as $colour) {
            $clash = false;
            foreach ($neighbours[$area] ?? [] as $n) {       // check the constraints
                if (($assigned[$n] ?? null) === $colour) { $clash = true; break; }
            }
            if ($clash) continue;
            $assigned[$area] = $colour;                      // choose
            if ($solve($i + 1)) return true;                 // explore
            unset($assigned[$area]);                         // un-choose
        }
        return false;                                        // no colour fits: back up
    };
    return $solve(0) ? $assigned : null;
}

$edges = [['A', 'C'], ['B', 'C'], ['A', 'D'], ['C', 'D'], ['B', 'E'], ['C', 'E'], ['D', 'E']];
$result = colourMap(['A', 'B', 'C', 'D', 'E'], $edges, ['Red', 'Green', 'Blue']);
foreach ($result as $area => $colour) {
    echo $area . ' = ' . $colour . "\n";
}

JavaScript

// Colour areas so that no two neighbouring areas share a colour (backtracking CSP).
function colourMap(areas, edges, colours) {
  const neighbours = {};
  for (const [a, b] of edges) {
    (neighbours[a] = neighbours[a] || []).push(b);
    (neighbours[b] = neighbours[b] || []).push(a);
  }
  const assigned = {};
  function solve(i) {
    if (i === areas.length) return true;                    // every variable assigned
    const area = areas[i];
    for (const colour of colours) {
      const clash = (neighbours[area] || []).some((n) => assigned[n] === colour);  // constraints
      if (clash) continue;
      assigned[area] = colour;                              // choose
      if (solve(i + 1)) return true;                        // explore
      delete assigned[area];                                // un-choose
    }
    return false;                                           // no colour fits: back up
  }
  return solve(0) ? assigned : null;
}

const edges = [['A', 'C'], ['B', 'C'], ['A', 'D'], ['C', 'D'], ['B', 'E'], ['C', 'E'], ['D', 'E']];
const result = colourMap(['A', 'B', 'C', 'D', 'E'], edges, ['Red', 'Green', 'Blue']);
for (const area in result) {
  console.log(area + ' = ' + result[area]);
}

Java

import java.util.*;

public class Main {
    // Colour areas so that no two neighbouring areas share a colour (backtracking CSP).
    // Returns null if it cannot be done.
    static Map<String, String> colourMap(List<String> areas, String[][] edges, List<String> colours) {
        Map<String, List<String>> neighbours = new HashMap<>();
        for (String[] e : edges) {
            neighbours.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]);
            neighbours.computeIfAbsent(e[1], k -> new ArrayList<>()).add(e[0]);
        }
        Map<String, String> assigned = new LinkedHashMap<>();
        return solve(0, areas, neighbours, colours, assigned) ? assigned : null;
    }

    static boolean solve(int i, List<String> areas, Map<String, List<String>> neighbours,
                         List<String> colours, Map<String, String> assigned) {
        if (i == areas.size()) return true;                      // every variable assigned
        String area = areas.get(i);
        for (String colour : colours) {
            boolean clash = false;
            for (String n : neighbours.getOrDefault(area, List.of())) {   // check the constraints
                if (colour.equals(assigned.get(n))) { clash = true; break; }
            }
            if (clash) continue;
            assigned.put(area, colour);                          // choose
            if (solve(i + 1, areas, neighbours, colours, assigned)) return true;   // explore
            assigned.remove(area);                               // un-choose
        }
        return false;                                            // no colour fits: back up
    }

    public static void main(String[] args) {
        String[][] edges = {{"A", "C"}, {"B", "C"}, {"A", "D"}, {"C", "D"}, {"B", "E"}, {"C", "E"}, {"D", "E"}};
        var result = colourMap(List.of("A", "B", "C", "D", "E"), edges, List.of("Red", "Green", "Blue"));
        for (var entry : result.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Go

package main

import "fmt"

// colourMap colours areas so that no two neighbouring areas share a colour (backtracking CSP).
// The second result is false if it cannot be done.
func colourMap(areas []string, edges [][2]string, colours []string) (map[string]string, bool) {
	neighbours := map[string][]string{}
	for _, e := range edges {
		neighbours[e[0]] = append(neighbours[e[0]], e[1])
		neighbours[e[1]] = append(neighbours[e[1]], e[0])
	}
	assigned := map[string]string{}
	var solve func(i int) bool
	solve = func(i int) bool {
		if i == len(areas) { // every variable assigned
			return true
		}
		area := areas[i]
		for _, colour := range colours {
			clash := false
			for _, n := range neighbours[area] { // check the constraints
				if assigned[n] == colour {
					clash = true
					break
				}
			}
			if clash {
				continue
			}
			assigned[area] = colour // choose
			if solve(i + 1) {       // explore
				return true
			}
			delete(assigned, area) // un-choose
		}
		return false // no colour fits: back up
	}
	return assigned, solve(0)
}

func main() {
	edges := [][2]string{{"A", "C"}, {"B", "C"}, {"A", "D"}, {"C", "D"}, {"B", "E"}, {"C", "E"}, {"D", "E"}}
	areas := []string{"A", "B", "C", "D", "E"}
	result, ok := colourMap(areas, edges, []string{"Red", "Green", "Blue"})
	if !ok {
		fmt.Println("No colouring")
		return
	}
	for _, area := range areas { // maps have no order, so walk the areas in order
		fmt.Println(area, "=", result[area])
	}
}

Time: O(d^n) · Extra space: O(n). In the worst case we try d values for each of n variables. Checking rules as we go cuts off most branches long before that.

Watch out for

  • Checking the constraints only after everything is assigned. Check at every step to prune early.
  • Not removing the assignment when backtracking, so a stale colour keeps blocking neighbours.
  • Assuming a solution always exists. Return a clear "no solution" when every branch fails.

Quick check

  1. What are the three ingredients of a constraint satisfaction problem?
    • Variables, domains, constraints
    • Stack, queue, heap
    • Nodes, edges, weights
  2. Why check the rules after each assignment?
    • To prune bad branches early
    • To sort the variables
    • To make the answer longer
  3. An area has no legal colour. What next?
    • Return failure so the previous area changes
    • Pick a clashing colour anyway
    • Delete the area