Greedy graph colouring
Take the nodes by degree (Welsh–Powell) and give each one the smallest colour none of its neighbours has.
Graph colouring gives every node a colour so that no two neighbours share one (think exam scheduling: courses with a common student must not be at the same time). Finding the fewest colours (the chromatic number) is NP-hard; the greedy method is fast but not always optimal.
Read the full explanation ↓- Time:
O(V log V + E) - Space:
O(V) - Grimaldi, chapter 11
- Johnsonbaugh, chapter 8
Seven nodes; the busiest nodes are coloured first and three colours are enough.
def greedy_coloring(graph, src):# Welsh-Powell: colour the nodes with the most neighbours first.order = sorted(graph, key=lambda v: -len(graph[v]))color = {v: 0 for v in graph}for u in order:used = set()for v, _ in graph[u]:if color[v] != 0:used.add(color[v])c = 1while c in used:c = c + 1color[u] = creturn color
Start
- Current node
(u) - Shortest-path tree so far
- Edge being checked
Local variables
Orange = changed in this step
graph dict
- 'A': [('B', 1), ('C', 1)]
- 'B': [('A', 1), ('C', 1), ('D', 1)]
- 'C': [('A', 1), ('B', 1), ('D', 1), ('E', 1)]
- 'D': [('B', 1), ('C', 1), ('F', 1)]
- 'E': [('C', 1), ('F', 1), ('G', 1)]
- 'F': [('D', 1), ('E', 1), ('G', 1)]
- 'G': [('E', 1), ('F', 1)]
Call stack
- greedy_coloring()line 1
How the work grows with input size
Average of 5 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- look
- current input (n=7)
Show as a table
| n | look |
|---|---|
| 4 | 10.4 |
| 8 | 27.6 |
| 12 | 41.6 |
| 16 | 56 |
| 20 | 70.8 |
| 24 | 74.4 |
| 28 | 94.4 |
Explanation
The idea
Graph colouring gives every node a colour so that no two neighbours share one (think exam scheduling: courses with a common student must not be at the same time). Finding the fewest colours (the chromatic number) is NP-hard; the greedy method is fast but not always optimal.
The algorithm
- Sort the nodes by degree, largest first (Welsh–Powell).
- Take the nodes in that order and give each the smallest colour none of its coloured neighbours has.
It uses at most Δ + 1 colours (Δ is the largest degree).
What to watch in the trace
- The number by each node is its colour (0 means not coloured yet).
- Try "a bad order": a graph that two colours would do gets four.