问题描述
解析
使用到了邻接矩阵
还有就是color数组,也是解题的关键,要明确color数组代表的含义:color[n],大小为n,下标肯定代表顶点,里面的值代表这个顶点放的是哪种颜色。
Traceback(t)的t代表某一个顶点,这个顶点具体放哪种颜色不知道,肯定有个for循环从第一种颜色到最后一种颜色都要试一下,那么color[t]里就放当前这种颜色。OK(t)判断一下,如果可以,traceback(t+1)。
OK(t)中,t顶点和哪些顶点有联系,我就去判断这些点放置的颜色有没有和我相同,若有相同的,return false;否则,return true。
代码
#include<stdio.h>
#define n 5 //图有多少个点
#define m 4 //色数m
int count=0; //方案数量
int color[n]={0}; //第i个点里面放的是哪一种颜色
int a[n][n]={0,1,1,1,0, //a数组代表无向图的邻接矩阵
1,0,1,1,1,
1,1,0,1,0,
1,1,1,0,1,
0,1,0,1,0};
bool OK(int t){
for(int j=0;j<n;j++){
if(a[t][j]==1){
if(color[t]==color[j])
return false;
}
}
return true;
}
void traceback(int t){
int oldvalue=0;
if(t==n){ //n个点都已经走完
count++;
return;
}
for(int i=1;i<=m;i++){ //i代表颜色
oldvalue=color[t];
color[t]=i;
if(OK(t)){
traceback(t+1);
}
color[t]=oldvalue;
}
}
int main(){
traceback(0); //t代表无向图的顶点
printf("%d\n",count);
return 0;
}