图的m着色和会场分配问题是一样的
题目描述:给定无向图G和m种颜色,用这些颜色给图的顶点着色,每个顶点一种颜色。若要求G的每条边的两个顶点着不同颜色,给出所有可能的着色方案。
#include <iostream>
using namespace std;
const int N = 50;
int color[N] = { 0 };
int trace[N] = { 0 };
int graph[N][N] = { 0 };
int PointNum; int methods, color_limit;
void Initiate()
{
cout << "请输入点个数: " << endl;
cin >> PointNum;
cout << "请输入颜色数" << endl;
cin >> color_limit;
cout << "请您依据图中节点的邻接关系输入邻接矩阵graph[][] " << endl;
for (int i = 1; i <= PointNum; ++i)
for (int j = 1; j <= PointNum; ++j)
{
cin >> graph[i][j];
}
}
//判断该点着此种颜色是否与邻点重复
bool OK(int i)
{
for (int m = 1; m <= PointNum; ++m)
{
if ((graph[i][m]==1)&&(color[m]== color[i]))
return false;
}
return true;
}
void Traceback(int i)
{
if (i > PointNum)
{
methods++;
//return 1;
}
else
{
for (int k = 1; k <= color_limit; ++k)
{
color[i] = k;
if (OK(i))
{
Traceback(i + 1);
}
color[i] = 0;//color[i] = 0;必须有,若去掉,当遇到某点对所有颜色都不合适的时候,该点将保留颜色编号最大的颜色color[color_limit]
//这样的话再回溯i-1的节点是不对的,对于i之前的节点比如i-1,color[i]应为0
}
}
}
int main()
{
Initiate();
Traceback(1);
cout << "一共" << methods << "种" << "着色方法" << endl;
return 0;
}
参考:https://blog.csdn.net/jeffleo/article/details/54586046
转载需要注明出处:https://blog.csdn.net/qq_34793133/article/details/80696862