Raaj Banga · Source on GitHub
Color a graph so neighbors never match, use all k colors, and keep the color groups as close in size as possible.
Same format the program reads: k, then n, then the n × n adjacency matrix with spaces between entries. Up to 64 vertices. Edit it, then press Color.
The coloring the program prints for this input.
Exactly what ./coloring input.txt prints.
Sort the group sizes and add up the gaps between neighbors. The middle numbers cancel out, so the score is just the biggest group minus the smallest.
The best possible score is 0 when k divides n evenly and 1 otherwise. The program stops as soon as it reaches that score, because nothing can beat it.
Given a graph and a number of colors k, color every vertex so that:
If no coloring follows the first two rules, the program prints “no such a sequence exists.”
Both solvers always find the best score. DP takes about the same time on every graph of a given size, but its memory doubles with every vertex, so it is only used up to 16 vertices.
An answer exists exactly when the graph can be colored with k colors. For k = 3 that question is the 3-coloring problem, which is NP-complete.
No polynomial-time method is known, so the program has to search. The work goes into pruning that search: skipping branches that can't lead to a better answer.
A graph often has several best colorings. The program always prints the same one:
Step with ← →, play with Space. One step is one call to search().
Color one vertex at a time. If a vertex has no legal color left, undo the last choice and try the next one. Keep the best coloring found so far.
The color class bars show the state of the search:
Trying everything takes far too long, so four rules cut the search down:
From most equal to least equal. The first range that works gives the best score.
Blue: sizes allowed in this step. Outlined: n / k, the perfectly even size.
Step with ← →, play with Space.
Instead of coloring one vertex at a time, build the coloring one whole color group at a time.
The table has one entry per set of vertices (2ⁿ of them), so the program uses DP only up to 16 vertices.
Search steps on this graph as each pruning rule is switched on.
Which rule matters most depends on the graph. Try “Star with 39 leaves”: bounding does almost all of the work there.
The numbers behind the chart, measured in your browser.
Measured on random graphs with k = 3 (from the report).
Each extra 2 vertices make DP about 9 times slower (3² = 9), as the analysis predicts. At 20 vertices it already takes a second, which is why bigger graphs use branch and bound.
n is the number of vertices. The input is an n × n grid, so the input size is N = n².
| Part | Time | Memory |
|---|---|---|
| Read, check, print | O(n²) | O(n²) |
| Dynamic programming (n ≤ 16) | O(n² · 3ⁿ) | O(2ⁿ) |
| Branch and bound (n > 16) | O(kⁿ · k²) | O(n) |