给定无向连通图和m种不一样的颜色。用这些颜色为图G的各顶点着色,每一个顶点着一种颜色。是否有一种着色法使G中每条边的两个顶点有不一样的颜色。算法
这个问题是图的m可着色断定问题。若一个图最少须要m种颜色才能使图中每条边相链接的两个顶点着不一样颜色,称这个数m为这个图的色数。数组
求一个图的色数m称为图的m可着色优化问题。 给定一个图以及m种颜色,请计算出涂色方案数。函数
分析:
细致分析后,t表明顶点仍是能分析出来的。
使用到了邻接矩阵
还有就是color数组,也是解题的关键,要明确color数组表明的含义:color[n],大小为n,下标确定表明顶点,里面的值表明这个顶点放的是哪一种颜色。
Traceback(t)的t表明某一个顶点,这个顶点具体放哪一种颜色不知道,确定有个for循环从第一种颜色到最后一种颜色都要试一下,那么color[t]里就放当前这种颜色。OK(t)判断一下,若是能够,traceback(t+1)。
OK(t)中,t顶点和哪些顶点有联系,我就去判断这些点放置的颜色有没有和我相同,如有相同的,return false;不然,return true。优化
#include
#include
#define V 4//图中的顶点数
/* 打印解决方案的实用函数 */
void printSolution(int color[])
{
printf(" Following are the assigned colors \n");
for (int i = 0; i < V; i++)
printf(" %d ", color[i]);
printf("\n");
}
bool isSafe(int v, bool graph[V][V], int color[], int c)用于检查当前颜色分配的实用程序函数
{
for (int i = 0; i < V; i++)
if (graph[v][i] && c == color[i])
return false;
return true;
}
void graphColoring(bool graph[V][V], int m, int color[], int v)//求解m着色问题的递推效用函数
{
if (v == V)//基本状况:若是全部顶点都指定了颜色,则返回真
{
printSolution(color);
return;
}
/* 考虑这个顶点v并尝试不一样的颜色*/
for (int c = 1; c <= m; c++)
{
/* 检查颜色C到V的分配是否正确*/
if (isSafe(v, graph, color, c))
{
color[v] = c;
/* 递归为其他顶点指定颜色 */
graphColoring(graph, m, color, v + 1);
/* 若是指定颜色C不会致使解决方案而后删除它 */
color[v] = 0;
}
}
}
// driver program to test above function
int main()
{
/* Create following graph and test whether it is 3 colorable
(3)---(2)
| / |
| / |
| / |
(0)---(1)
*/
bool graph[V][V] = { { 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 1 },
{ 1, 0, 1, 0 },
};
int m = 3; // Number of colors
int color[V];
for (int i = 0; i < V; i++)
color[i] = 0;
graphColoring(graph, m, color, 0);
system("pause");
return 0;
}
运行结果:spa