回溯法--图的m着色问题
题目描述
给定无向连通图G(N,E),含有n个结点,k条边。现在有m种颜色,现在要给n个结点涂色,要求相邻结点不同色。求共有多少种涂色方案。
输入第一行3个整数n,k,m;
接下来k行,每行两个数,u,v表示u,v结点有一条无向边。
输出2行
第一行一个整数x表示方案数。
题目思路
- 遍历每一种染色方法
题目代码
/*
3 3 3
1 2
1 3
2 3
6
*/
#include <iostream>
using namespace std;
const int N = 10;
int n; // 图的顶点数
int m; // 可用颜色数
int a[N][N]; // 图的邻接矩阵
int x[N]; // 当前解
long long sum; // 当前已找到的可m着色方案数
bool Ok(int k)
{
for(int j = 1; j <= n; j ++ )
if((a[k][j] == 1) && x[j] == x[k])
return false;
return true;
}
void Backtrack(int t)
{
if(t > n)
{
sum ++;
for(int i = 1; i <= n; i ++ )
cout << x[i] << " ";
cout << endl;
}
else
{
for(int i = 1; i <= m; i ++ )
{
x[t] = i;
if(Ok(t))
Backtrack(t + 1);
x[t] = 0;
}
}
}
int main()
{
int e;
cin >> n >> e >> m;
for(int i = 1; i <= e; i ++ )
{
int start, end;
cin >> start >> end;
a[start][end] = a[end][start] = 1;
}
Backtrack(1);
cout << sum << endl;
return 0;
}