// 4 color theorem #include #include #include #include #include /********************************************************************* Before you try to decipher this code, have a look at p555, a typical input file that describes a subgraph to color. Also review http://www.mathreference.com/gph-planar,5color.html type make to compile. Usage is 4ct inputfile(s) Example: 4ct p555 *********************************************************************/ typedef unsigned char uchar; static int debug; // Internal points are the actual subgraph described by the file. // Border is the ring around this subgraph. #define MAXINTERNAL 32 #define MAXBORDER 32 // number of internal points, and number of points on the border static int ninternal, nborder; // Edges, assumes average degree of 7 or less. #define MAXCONNECT (MAXINTERNAL*7) // error and abort static void eprint(const char *msg, int arg) { fprintf(stderr, msg, arg); fprintf(stderr, "\n"); exit(1); } static void eprints(const char *msg, const char *arg) { fprintf(stderr, msg, arg); fprintf(stderr, "\n"); exit(1); } static char *nextLine(FILE * f) { static char line[200]; while(1) { if(!fgets(line, sizeof (line), f)) return 0; if(line[0] == '#' || line[0] == '\n') continue; return line; } } // A list of internal points that make the perimeter. // The border lies just outside the perimeter. static uchar perimeter[MAXINTERNAL]; static int nperim; static uchar *patterns; // allocated static uchar *patternEnd; static int maxpattern, npattern; // Set to 1 for each pattern that is colorable. static uchar *colorable; // list of connections. [0] to [1] // conections among vertices in the input graph have a base of MAXBORDAR. static uchar connections[MAXCONNECT][2]; static int nedges; // Print a border for debugging purposes. static void printBorder(const uchar * b) { for(int i = 0; i < nborder; ++i) printf("%d", b[i]); printf("\n"); } static void goodBad(void) { int i; const uchar *p; if(!debug) return; puts("good"); for(i = 0; i < npattern; ++i) { if(!colorable[i]) continue; p = patterns + i * nborder; printBorder(p); } puts("bad"); for(i = 0; i < npattern; ++i) { if(colorable[i]) continue; p = patterns + i * nborder; printBorder(p); } puts("end"); } // Make the first color on the border red, next one blue, etc. static void normalizeColors(uchar * p) { int nc = 0; uchar list[8]; memset(list, 0, sizeof (list)); for(int i = 0; i < nborder; ++i) { uchar c = p[i]; if(!list[c]) list[c] = ++nc; p[i] = list[c]; } } // Add an edge from an internal point to a point on the border // Internal point number is bumped up by MAXBORDER. static void addEdge(int u, int v) { if(nedges == MAXCONNECT) eprint(" too many connections, limit %d", MAXCONNECT); if(debug) printf("%c %d\n", u + (u < 26 ? 'a' : 'A' - 26), v); connections[nedges][0] = u + MAXBORDER; connections[nedges][1] = v; ++nedges; } // turn a into 0, d into 3, A into 26, etc static int letterInternal(const char *line, char c) { // line is here only for error messages int j; if(islower(c)) j = c - 'a'; else if(isupper(c)) j = c - 'A' + 26; else eprints("letter expected in line %s", line); if(j >= ninternal) eprint("vertex %c is out of range", c); return j; } static void readGraph(const char *filename) { char *line, *s; int i, j; int shift = 0, reflect = 0; char rowmode = 0; int edeg; // external degree int edeg0; // external degree of first vertex FILE *f; // The degree of each internal point. uchar degree[MAXINTERNAL]; uchar extdegree[MAXINTERNAL]; f = fopen(filename, "r"); if(!f) eprints("cannot open file %s", filename); line = nextLine(f); if(!line) eprint("empty file", 0); ninternal = strtol(line, &s, 10); if(ninternal > MAXINTERNAL || ninternal <= 0) eprint("too many internal points", ninternal); if(*s == '+') shift = strtol(s + 1, &s, 10); if(*s == '^') reflect = 1; line = nextLine(f); if(!line) eprint("list of perimeter points and their degrees is expected", 0); s = line; if(*s == ';') { ++s, rowmode = 1; eprint("row mode not supported by this version", 0); } i = 0; while(isalpha(*s)) { if(i >= ninternal) eprint("too many points on the perimeter, as set by %d", ninternal); perimeter[i] = letterInternal(line, *s); for(j = 0; j < i; ++j) if(perimeter[j] == perimeter[i]) eprint("perimeter point %c is repeated", *s); degree[i] = strtol(s + 1, &s, 10); if(degree[i] < 5 || degree[i] > 15) eprint("degree %d out of range, please use 5 to 15", degree[i]); if(i) { connections[nedges][0] = perimeter[i - 1] + MAXBORDER; connections[nedges][1] = perimeter[i] + MAXBORDER; ++nedges; } while(*s == ' ') ++s; ++i; } nperim = i; if(i > 2 && !rowmode) { // another edge completes the circle connections[nedges][0] = perimeter[i - 1] + MAXBORDER; connections[nedges][1] = perimeter[0] + MAXBORDER; ++nedges; } if(*s != '\n') eprint("unexpected character %c in perimeter description", *s); if(nperim == 2 && !rowmode) eprint("2 vertices requires row mode", 0); while(line = nextLine(f)) { if(rowmode) eprints("line %s after perimeter in row mode", line); char preletter = 0; char firstletter = 0; uchar fan = 0; // fan set to 1 for a>bcd which connects a to b c and d, like a fan out j = 0; s = line; while(isalpha(*s)) { if(preletter) { if(nedges == MAXCONNECT) eprint(" too many connections, limit %d", MAXCONNECT); connections[nedges][0] = letterInternal(line, (fan ? firstletter : preletter)) + MAXBORDER; connections[nedges][1] = letterInternal(line, *s) + MAXBORDER; ++nedges; } preletter = *s; if(!j) firstletter = *s; ++j, ++s; while(*s == ' ') ++s; if(j == 1 && *s == '>') { fan = 1; ++s; while(*s == ' ') ++s; } } if(*s != '\n') eprints("syntax error in line %s", line); if(j > 2 && !fan) { if(nedges == MAXCONNECT) eprint(" too many connections, limit %d", MAXCONNECT); // another edge completes the circle connections[nedges][0] = letterInternal(line, preletter) + MAXBORDER; connections[nedges][1] = letterInternal(line, firstletter) + MAXBORDER; ++nedges; } // check for duplicates for(i=0; i= degree[i]) { fprintf(stderr, "internal degree of %c is %d; should be less than %d\n", perimeter[i] + (perimeter[i] < 26 ? 'a' : 'A' - 26), ideg, degree[i]); exit(1); } edeg = extdegree[i] = degree[i] - ideg; } // Set up the border. for(i = 0; i < nperim; ++i) { edeg = extdegree[i]; if(!i) { // first vertex edeg0 = edeg; edeg = (edeg + 1) / 2; } else { addEdge(perimeter[i], nborder - 1); --edeg; } while(edeg) { if(nborder >= MAXBORDER) eprint("too many border points, limit %d", MAXBORDER); addEdge(perimeter[i], nborder); ++nborder, --edeg; } } // Revisit the first vertex. edeg = edeg0 / 2; if(!edeg) { if(nborder > 1) { // special case; we shouldn't have created the last vertex --nborder; for(i=nedges-1; connections[i][1] == nborder; --i) connections[i][1] = 0; if(debug) printf("replace point %d with 0\n", nborder); } } else { addEdge(perimeter[0], nborder - 1); --edeg; } while(edeg) { if(nborder >= MAXBORDER) eprint("too many border points, limit %d", MAXBORDER); addEdge(perimeter[0], nborder); ++nborder, --edeg; } printf("%d border points\n", nborder); if(shift || reflect) printf("rotations and reflections are ignored\n"); } // Find the canonical pattern for a given pattern. // This is the first, lexicographically, in its equivalence class. // Leave the result in equivalent[]. static uchar equivalent[MAXBORDER]; static void findEquivalentPattern(const uchar * p) { memcpy(equivalent, p, nborder); normalizeColors(equivalent); } // patterns are a function of the border, having nothing to do with the // graph inside. This grows as 3^n, where n is border length - 2. static void buildPatterns(void) { int level, i; uchar b[MAXBORDER]; // make room for the first 1000 maxpattern = 1000; patterns = malloc(maxpattern * nborder); patternEnd = patterns + maxpattern * nborder; // Start with 2 prescribed colors, like red and blue. b[0] = 1, b[1] = 2; level = 1; push: if(++level == nborder) { findEquivalentPattern(b); if(!memcmp(b, equivalent, nborder)) { if(npattern == maxpattern) { if(patternEnd - patterns >= 40000000) eprint("too many patterns in ram; you have to redesign the program", 0); maxpattern = maxpattern * 3 / 2; patterns = realloc(patterns, maxpattern * nborder); patternEnd = patterns + maxpattern * nborder; } memcpy(patterns + npattern * nborder, b, nborder); ++npattern; } goto pop; } b[level] = 0; next: if(++b[level] == 5) goto pop; if(b[level] == b[level - 1]) goto next; if(level == nborder - 1 && b[level] == 1) goto next; goto push; pop: if(--level > 1) goto next; printf("%d patterns\n", npattern); } // Color the internal points based on a given boundary. // Return true if it can be done. static int colorInternal(const uchar * b) { uchar x[MAXINTERNAL]; uchar c, v; int level = -1; push: if(++level == ninternal) return 1; x[level] = 0; next: c = ++x[level]; if(c == 5) goto pop; v = MAXBORDER + level; // v is a representation of the vertex in our graph, within the list of edges. for(int k = 0; k < nedges; ++k) { uchar other; if(connections[k][0] == v) other = connections[k][1]; else if(connections[k][1] == v) other = connections[k][0]; else continue; if(other > v) continue; // not yet colored // other has to be different from c if(other < MAXBORDER && b[other] == c) goto next; if(other >= MAXBORDER && x[other - MAXBORDER] == c) goto next; } goto push; pop: if(--level >= 0) goto next; return 0; } static const uchar *cp; // current pattern static uchar cpc[MAXBORDER]; // current pattern copy // Is the equivalent pattern (of the copy) colorable? static int equivalentColorable(void) { int i, l, r, d; // for binary search findEquivalentPattern(cpc); l = -1, r = npattern; while(r - l > 1) { i = (l + r) / 2; d = memcmp(equivalent, patterns + i * nborder, nborder); if(!d) return colorable[i]; if(d < 0) r = i; else l = i; } eprint("equivalent pattern not found", 0); } // swap c1 and c2, or c3 and c4 static uchar c1, c2, c3, c4; static uchar band[MAXBORDER]; static uchar bandstart[MAXBORDER]; static int nbands; static void findBands(void) { int i; // first chunk of the border belongs to band 1 nbands = 1; band[0] = 1; bandstart[1] = 0; for(i = 1; i < nborder; ++i) { uchar u = cp[i], v = cp[i - 1]; if(u == c4) u = c3; if(u == c2) u = c1; if(v == c4) v = c3; if(v == c2) v = c1; if(v != u) { ++nbands; // start of new band bandstart[nbands] = i; } band[i] = nbands; } // rbrbrbrb or rbrygy if(nbands <= 2) return; // starts with r or b, ends in y or g if(!(nbands & 1)) return; // last band is really part of the first rbrygyb for(i = nborder - 1; band[i] == nbands; --i) band[i] = 1; --nbands, ++i; bandstart[1] = i; } // act within the copy of the color pattern static void swapBand(int n) { uchar total; ++n; int j = bandstart[n]; if(cpc[j] == c1 || cpc[j] == c2) total = c1 + c2; else total = c3 + c4; while(band[j] == n) { cpc[j] = total - cpc[j]; if(++j == nborder) j = 0; } } #define cpRestore() memcpy(cpc, cp, nborder) #define bandOver(v, n) v = start + n; if(v >= nbands) v -= nbands; #define bandUnder(v, n) v = start - n; if(v < 0) v += nbands; static int chainColorable2(void) { int i, j, rc; int start, start1, start_1, start2, start_2, start3, start_3; findBands(); // If all rbrbrbrb and we swap r and b, nothing to do. // If rbrbrbgygygy and we swap r and b, or g and y, nothing to do. if(nbands < 4) return 0; // beyond the limits of this program - no way should we have 29 bands. if(nbands > 28) { printf("%d bands is beyond limit\n", nbands); return 0; } if(nbands == 4) { cpRestore(); swapBand(0); rc = equivalentColorable(); if(!rc) return 0; cpRestore(); swapBand(1); rc = equivalentColorable(); if(rc && debug) { printf("%d bands %d%d 0f ", nbands, c1, c2); printBorder(cp); } return rc; } int yescount = 0, m = 0; // m is a mask of the single arcs that flip and work for(i=0; i= 5) return 1; if((m&7) == 7 || (m&0xe) == 0xe || (m&0x1c) == 0x1c || (m&0x38) == 0x38 || (m&0x31) == 0x31 || (m&0x23) == 0x23) return 1; if(yescount == 3) return 0; // now yescount is 4 but not 3 in a row if(!(m&1)) i = 0; if(!(m&2)) i = 1; if(!(m&4)) i = 2; cpRestore(); swapBand(i); swapBand(i+3); rc = equivalentColorable(); if(rc && debug) printf("across,%d,%d\n", i, i+3); return rc; } /* Single flip, flip one arc and assume it works. Call it a red arc (or a red blue arc if you prefer), and say it is band 0. Fine, but what if this chains around to another red arc? Let j be the first red arc, travelling clockwise, that is chained to 0. If j is 2, then I need to flip 1. If j is -2, then I need to flip -1. These single flips are efficiently checked by the mask m, and that's the first thing we do. To illustrate say j is 12. 1 connects by a yello chain to 11. If it didn't then 12 would not be the first arc connected to 0. This yellow chain holds the red chain away from arcs 2 4 6 8 10. The yellow chain could connect to some of the yellow arcs inside, such as 7. Or it might not. Or it might connect to all of them. We must guard against this last possibility. We need to flip all the yellow arcs beneath this red chain. Call this set of arcs S. In this case 1 3 5 7 9 11. If the yellow chain doesn't connect to all the arcs in S, then maybe we don't have to flip all of them, but we might have to flip all of them, and we can flip all of them, so that is the test. Flip the set S, for every odd j, as we march around. We don't have to test j = 1, we already verified that flip. We don't have to go up to j = -1, as band 0 connecting to itself is trivial. We don't have to consider j = -3. S is then the complement of -1, and we already verified that flip. So that is the algorithm. */ if(yescount >= 3) { if(debug) { printf("%d bands %d%d %02x ", nbands, c1, c2, m); printBorder(cp); } for(start = 0; start < nbands; ++start) { if(!(m&(1<= 2) { for(start = 0; start < nbands; ++start) { bandOver(start3, 3); if(!(m&(1< 8) { cpRestore(); swapBand(start); swapBand(start2); if(!equivalentColorable()) goto next_double; } cpRestore(); for(j = start3; j != start_1; j = (j + 2) % nbands) { swapBand(j); if(!equivalentColorable()) goto next_double; // switch between S and T swapBand(start1); if(!equivalentColorable()) goto next_double; } if(debug) { if(yescount == 2) { printf("%d bands %d%d %02x ", nbands, c1, c2, m); printBorder(cp); } printf("double,%d,%d\n", start, start2); } return 1; next_double: ; } } // Other versions of this program have considerably more tests. return 0; } #undef cpRestore #undef bandOver #undef bandUnder static int chainColorable1(void) { c1 = 1, c2 = 2, c3 = 3, c4 = 4; if(chainColorable2()) return 1; c1 = 1, c2 = 3, c3 = 2, c4 = 4; if(chainColorable2()) return 1; c1 = 1, c2 = 4, c3 = 2, c4 = 3; return chainColorable2(); } // number of connections for sewing, and number of lines for triangulation static int nsew, nlines; // indicate sewing with = and line with - // 3=5 sews 3 and 5 together, 3-5 is a line from 3 to 5 static void printLines(const char *msg, const uchar * a, const uchar * b) { printf("%s", msg); for(int j = 0; j < nsew + nlines; ++j) printf(" %d%c%d", a[j], (j < nsew ? '=' : '-'), b[j]); printf("\n"); } // Return 1 if this set of sewing and lines allows G to be colored. static int checkLines(const uchar * a, const uchar * b) { if(debug) printLines("lines", a, b); for(int i = 0; i < npattern; ++i) { if(colorable[i]) continue; // now it's a bad (uncolorable) pattern. cp = patterns + i * nborder; for(int j = 0; j < nsew + nlines; ++j) { /* If sewing points together, j < nsew, then those points have to have the same color. If a line is drawn between points, then those points have to have different colores. The exclusive or operator accomplishes this. */ if((j < nsew) ^ (cp[a[j]] == cp[b[j]])) { // this bad color pattern is mismatched. // That's good. Go on to the next pattern. goto next_pattern; } } // This pattern is not precluded by these lines, // and it remains uncolorable. if(debug) { printf("crash "); printBorder(cp); } return 0; next_pattern:; } return 1; // this configuration of lines does the trick! } // return 1 if the newest line crosses an earlier line. static int crossLines(uchar * a, uchar * b, int top) { uchar s, t, u, v; u = a[top], v = b[top]; if(v <= u) eprint("backward line at depth %d", top); for(int j = 0; j < top; ++j) { s = a[j], t = b[j]; if(s == u) { if(t == v) return 1; // duplicate line continue; } if(t == v) continue; if((s > u && s < v) ^ (t > u && t < v)) return 1; } return 0; } // return 1 if graph becomes colorable using sewing and lines etc. static int drawLines(void) { // connect a[i] to b[i] uchar a[MAXBORDER], b[MAXBORDER]; uchar le[MAXBORDER]; // line equivalence int linecount = 0; int sp = -1; // stack pointer int k, sewtop; /* sewtop is the number of sewing connections that must be made in the border. It loops from 0 up to (but not including) nborder/2. In a hexagon, nborder = 6, we can sew 0 pairs of points together, 1 pair, or 2 pair. This function won't return success unless nsew, the number of sewings, equals sewtop. The rest is filled in with lines for triangulation. A push pop stack sets the sewing connections first, then lines. First time through the loop, sewtop is 0, there is no sewing, and all connections are lines drawn. After that, sewing must take place. sp == sewtop is a transition, when the number of sewing pushed onto the stack equals the number of sewing expected. Next connection pushed onto the stack will be a line drawn. nsew == sewtop is another transition, when we have enough sewing to test the arrangement against the uncolorable patterns and seeif we have precluded all of them. */ nsew = 0, nlines = 0; for(sewtop = 0; sewtop < nborder / 2; ++sewtop) { if(debug) printf("sewtop %d\n", sewtop); push: ++sp; if(nsew == sewtop && linecount == nborder - 3 && checkLines(a, b)) { printLines("ok lines", a, b); return 1; } // connect 0 to 1, which is impossible, but next will step us through a[sp] = 0, b[sp] = 1; // We have to be past the last line or sew that we made. // But not if we are transitioning from sewing to lines. // Copying the previous connection is impossible, but next will step us through. if(sp && sp != sewtop) a[sp] = a[sp - 1], b[sp] = b[sp - 1]; next: if(++b[sp] >= nborder) { if(++a[sp] >= nborder) goto pop; b[sp] = a[sp] + 1; goto next; } // the other side of the cycle if(a[sp] == 0 && b[sp] == nborder - 1) goto next; if(crossLines(a, b, sp)) goto next; /* If 3 and 5 sew together, and we want a connection from (3,5) to 7, then 3-7 and 5-7 are semantically the same. I don't want to do things twice. */ if(sp && sp < sewtop) { for(k = 0; k < sp; ++k) { if(b[k] == a[sp]) goto next; if(b[k] == b[sp]) goto next; } // we can't sew 3 to 7, and then 3 to 8, that squashes 7 and 8 and those are // adjacent countries with different colors. if(a[sp] == a[sp - 1] && b[sp] == b[sp - 1] + 1) goto next; } if(sewtop && sp >= sewtop) { for(k = 0; k < sewtop; ++k) { if(b[k] == a[sp]) goto next; if(b[k] == b[sp]) goto next; if(a[k] == a[sp] && b[k] == b[sp] + 1) goto next; if(a[k] == a[sp] && b[k] == b[sp] - 1) goto next; if(a[sp] == 0 && b[sp] == a[k] && b[k] == nborder - 1) goto next; } } le[sp] = 1; if(sp < sewtop) { ++nsew; le[sp] = 3; // the count changes if we are sewing one side of a triangle, // quashing it down to a line. if(b[sp] == a[sp] + 2) --le[sp]; if(a[sp] == 0 && b[sp] == nborder - 2) --le[sp]; if(a[sp] == 1 && b[sp] == nborder - 1) --le[sp]; if(sp) { if(a[sp-1] == a[sp] && b[sp-1] + 2 == b[sp]) --le[sp]; for(k = 0; k < sp; ++k) { if(a[k] + 2 == a[sp] && b[k] == b[sp]) --le[sp]; if(a[k] + 1 == a[sp] && b[k] - 1 == b[sp]) --le[sp]; if(a[k] == 0 && b[k] + 1 == a[sp] && b[sp] == nborder - 1) --le[sp]; } } } else ++nlines; linecount += le[sp]; goto push; pop: if(--sp >= 0) { linecount -= le[sp]; if(nlines) --nlines; else --nsew; goto next; } if(nlines || nsew) eprint("counts do not return to 0 after sewtop %d", sewtop); if(linecount) eprint("linecount does not return to 0 after sewtop %d", sewtop); } return 0; } int main(int argc, char **argv) { int i, colorCount, change; ++argv, --argc; if(argc && !strcmp(argv[0], "-d")) { debug = 1; ++argv, --argc; } if(argc == 0) eprint("usage: 4ct [-d] graph_file(s)", 0); top: npattern = nborder = ninternal = nperim = nedges = 0; colorCount = 0; puts(argv[0]); readGraph(argv[0]); buildPatterns(); colorable = malloc(npattern); memset(colorable, 0, npattern); for(i = 0; i < npattern; ++i) { cp = patterns + i * nborder; if(colorInternal(cp)) colorable[i] = 1, ++colorCount; } printf("%d patterns directly colorable\n", colorCount); if(colorCount == npattern) { puts("ok"); goto nextfile; } goodBad(); while(1) { change = 0; for(i = 0; i < npattern; ++i) { if(colorable[i]) continue; cp = patterns + i * nborder; if(!chainColorable1()) continue; colorable[i] = 1; ++colorCount; ++change; if(!debug) continue; printf("swap %d%d ", c1, c2); printBorder(cp); } if(!change) break; printf("%d colorable\n", change); if(colorCount < npattern) continue; puts("ok"); goto nextfile; } printf("unknown %d%%\n", (npattern - colorCount) * 100 / npattern); goodBad(); if(drawLines()) goto nextfile; return 1; nextfile: free(colorable); free(patterns); ++argv, --argc; if(argc) goto top; return 0; }