#include<iostream>
#include<iomanip>
using namespace std;
const int n = 5;
const int m = 4;
int sum = 0;
const int Graph[n][n] = {
{0,1,1,1,0},
{1,0,1,1,1},
{1,1,0,1,0},
{1,1,1,0,1},
{0,1,0,1,0}
};
int Color[n] = { 0 };//0是未着色状态
bool check(int c);//检查c点与已着色的邻接点颜色是否不同
void Print(int c,int Count=1);//给点c上色,Count记录有多少个点已经着色
int main()
{
Print(0);//初始状态只选取一个点,避免重复
return 0;
}
bool check(int c)
{
for (int i = 0; i < n; i++)
{
if ((Graph[c][i] == 1) && (Color[i] != 0) && (Color[i] == Color[c]))
//Graph[c][i]==1表示i是c的邻接点,Color[i]!=0表示i已经上色,Color[i]==Color[c]表示i和c上色的颜色相同
return false;
}
return true;
}
void Print(int c,int Count)
{
for (int k = 1; k <= m; k++)
{
Color[c] = k;
if (check(c))//着色成功
{
if (Count == n)//所有点都已经着色
{
cout<<"No." << ++sum <<": ";
for (int i = 0; i < n; i++)
cout << setw(3) << Color[i];
cout << endl;
}
else
{
for (int i = c+1; i < n; i++)
{
if ((Graph[c][i] == 1) && (Color[i] == 0))
//Graph[c][i]==1表示i是c的邻接点,Color[i]==0表示i没有着过色
Print(i, Count + 1);
}
}
}
}
Color[c] = 0;
return;
}
图的m着色问题
最新推荐文章于 2021-12-01 21:23:01 发布