#include <iostream>
#include <fstream>
using namespace std;
class Color
{
friend int mColoring(int,int,int**);
private:
bool Ok(int k);
void Backtrack(int t);
int n, //图的顶点数
m, //可用颜色数
**a, //图的邻接矩阵
*x; //当前解
long sum; //当前已找到的可m着色方案数
};
bool Color::Ok(int k) //检查颜色的可用性
{
for(int j=1;j<=n;j++)
{
if((a[k][j]==1)&&(x[j]==x[k]))
{
return false;
}
}
return true;
}
void Color::Backtrack(int t)
{
if(t>n)
{
sum++;
for(int i=1;i<=n;i++)
cout<<x[i]<<" ";
cout<<"\n";
}else{
for(int i=1;i<=m;i++)
{
x[t]=i;
if(Ok(t))
Backtrack(t+1);
x[t]=0;
}
}
}
int mColoring(int n,int m,int **a)
{
Color X;
//初始化X
X.n = n;
X.m = m;
X.a = a;
X.sum = 0;
int *p = new int [n+1];
for(int i=0;i<=n;i++)
p[i]=0;
X.x = p;
X.Backtrack(1);
delete [] p;
return X.sum;
}
int main()
{
ifstream input("input.txt");
ofstream output("output.txt");
int n,m,**arr;
input>>n>>m;
cout<<n<<" "<<m<<"\n";
arr = new int* [n+1];
for(int i=1;i<=n;i++)
{
*(arr+i) = new int [n+1];
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
input >> arr[i][j];
cout << arr[i][j] << " ";
}
cout << "\n";
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout << arr[i][j] << " ";
output << arr[i][j] << " ";
}
cout<<"\n";
output<<"\n";
}
output << "\n";
cout<<"\n";
cout<<"\n"<<mColoring(n,m,arr)<<"种\n";
return 0;
}
图的m着色问题 回溯法
猜你喜欢
转载自blog.csdn.net/qq_29856169/article/details/90217492
今日推荐
周排行