图的m着色问题
问题: 图的m着色问题。给定无向连通图G和m种颜色,用这些颜色给图的顶点着色,每个顶点一种颜色。如果要求G的每条边的两个顶点着不同颜色。给出所有可能的着色方案;如果不存在,则回答“NO”。
解析: 图着色问题描述为: 给定无向连通图G=(V, E)和正整数m,求最小的整数m,使得用m种颜色对G中的顶点着色.使得任意两个相邻顶点着色不同。这个问题是图的m可着色判定问题。若一个图最少需要m种颜色才能使图中每条边连接的2个顶点着不同颜色,则称这个数m为该图的色数。求一个图的色数m的问题称为图的m可着色优化问题。
设计:
void dfs(int cur){
if (cur > n){
printf("programme %d:", number++);
for (int i = 1; i <= n; i++){
printf("%d ", color[i]);
}
res++;
printf("\n");
}else{
for (int i = 1; i <= m; i++){
color[cur] = i;
if (check(cur)){
dfs(cur + 1);
}
color[cur] = 0;
}
}
}
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 10;
int a, b, n, res, m;
int graph[maxn][maxn], color[maxn];
bool check(int i){
for (int j = 1; j <= n; j++){
if (graph[i][j] && color[i] == color[j]){
return false;
}
}
return true;
}
int number = 1;
void dfs(int cur){
if (cur > n){
printf("programme %d:", number++);
for (int i = 1; i <= n; i++){
printf("%d ", color[i]);
}
res++;
printf("\n");
}else{
for (int i = 1; i <= m; i++){
color[cur] = i;
if (check(cur)){
dfs(cur + 1);
}
color[cur] = 0;
}
}
}
int main(){
for (int i = 0; i < maxn; i++)
for (int j = 0; j < maxn; j++)
graph[i][j] = 0;
printf("please input n and m:\n");
scanf("%d %d", &n, &m);
printf("Please enter the point of each edge:\n");
for (int i = 1;; i++){
scanf("%d %d", &a, &b);
if (a == 0 && b == 0)
break;
graph[a][b] = 1;
graph[b][a] = 1;
}
dfs(1);
if (res == 0)
printf("No\n");
else
printf("result = %d\n", res);
return 0;
}
分析:
O(nm^n )
github源码地址:
传送门