1. 问题
给定无向连通图G和m种颜色,用这些颜色给图的顶点着色,每个顶点一种颜色。
要求:G的每条边的两个顶点着不同颜色。
给出所有可能的着色方案;如果不存在,则回答“NO”。
2. 解析
在填写每一个顶点的颜色时检查与相邻已填顶点的颜色是否相同。如果不同,则可以填入该颜色;如果相同(冲突),则另选一种;如果已没有颜色可供选择,则回溯到上一顶点。重复这一过程,直到所有顶点的颜色都已填上。
3. 设计
#include<iostream>
using namespace std;
int c[100][100]; //邻接矩阵
int color[100]; //记录每个顶点的颜色
int sum, m, n; //count记录方案数 n个顶点 m种颜色
int Check(int k) //检查第i个顶点的颜色是否满足条件
{
for (int i = 1; i <= k; i++)
{
if (c[k][i] == 1 && color[i] == color[k]) //k与i之间相连并且i顶点的颜色与k顶点的颜色相同
return 0;
}
return 1;
}
void GraphColor(int step)
{
if (step == n + 1) //表示前面所有的顶点颜色都已经填完
{
for (int i = 1; i <= n; i++)
printf("%d ", color[i]);
sum++;
printf("\n");
return;
}
else
{
for (int i = 1; i <= m; i++)
{
color[step] = i; //首先将这个顶点颜色换为i
if (Check(step) == 1) //检查是否符合条件
{
GraphColor(step + 1); //符合条件则走下一步
}
color[step] = 0; //回溯 置为0
}
}
}
int main(void)
{
cout << "输入顶点数:";
cin >> n;
cout << "输入有多少种颜色可选:";
cin >> m;
cout << "输入图的邻接矩阵:" << endl;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
cin >> c[i][j];
}
GraphColor(1);
if (sum == 0)
cout<<"NO";
else
cout<<sum;
return 0;
}
4. 分析
时间复杂度O(n)=m²