题目:http://acm.jlu.edu.cn/joj/showproblem.php?pid=1003
图的着色问题。因为已知任何平面图都可以用不多于四种的颜色进行着色,并且使相邻顶点的颜色不同。所以分别使用1,2,3,4四种颜色进行试探。使用回溯法,代码如下:
- #include <stdio.h>
- #include <string.h>
- int repeaters,net[26][26],l,c,i,j,color,s[26];
- bool colorMap(int net[26][26],int count) {
- memset(s, 0, sizeof(s));
- s[0] = 1;
- int i = 1,j = 1,c;
- while(i < repeaters) {
- while(i >= 0 && j <= count && i < repeaters) {
- for(c = 0; c < i; c++)
- if(s[c] * net[i][c] == j) break;
- if(c < i) j++;
- else {s[i] = j;i++;j = 1;}
- if(j > count) {
- while(i >= 0 && j > count) { //多次回溯
- i--; j = s[i] + 1;
- }
- }
- }
- if(i < 0 ) return false;
- }
- return true;
- }
- int main() {
- char from,to;
- while(scanf("%d", &repeaters), repeaters) {
- memset(net, 0, sizeof(net));
- for(i = 0; i < repeaters; i++) {
- if((from = getchar()) == '/n') from = getchar();
- l = (int)(from - 'A');
- while((to = getchar()) != '/n') {
- if(to == ':') continue;
- c = (int)(to - 'A');
- net[l][c] = 1;
- }
- }
- for(i = 1; i <= 4; i++) {
- if(colorMap(net, i)) {color = i; break;}
- }
- if(color == 1)
- printf("1 channel needed./n");
- else
- printf("%d channels needed./n", color);
- }
- return 0;
- }
其中,全局变量net[26][26]是图的邻接矩阵,net[i][j]值为1表示顶点i与顶点j相邻。全局变量s数组表示顶点所用的颜色。colorMap函数表示使用count种颜色对图进行试探着色,如果试探成功,则返回1,否则返回0。全局变量repeaters表示顶点数目。