项湫

导航

图的m着色问题

1. 问题

给定无向连通图G和m种颜色,用这些颜色给图的顶点着色,每个顶点一种颜色。如果要求G的每条边的两个顶点着不同颜色。给出所有可能的着色方案;如果不存在,则回答“NO”。

 

2. 解析

在填写每一个顶点的颜色时检查与相邻已填顶点的颜色是否相同。如果不同,则填上;如果相同(冲突),则另选一种;如果已没有颜色可供选择,则回溯到上一顶点。重复这一过程,直到所有顶点的颜色都已填上。

  使用color[n],大小为nn代表顶点,里面的值代表这个顶点放的是哪种颜色。

  Tracebackt)的t代表某一个顶点,for循环从第一种颜色遍历到最后一种颜色,那么color[t]里就放当前这种颜色。OKt)判断一下,如果可以,tracebackt+1)。

  OKt)中,观察t顶点和哪些顶点有联系,判断这些点放置的颜色有无相同,若有,return false;否则,return true

3. 设计

void Trackback(int t) { //回溯

if (t > n) {

count++;

for (int i = 1; i <= n; i++)

printf("%d ", color[i]);

printf("\n");

}

else {

for (int i = 1; i <= m; i++) {  //颜色小于色数

color[t] = i;

if (Ok(t))

{

Trackback(t + 1);

}

color[t] = 0;

}

}

}

4. 分析

时间复杂度为O(n^m)

5. 源码

#include<stdio.h>

#include<string.h>

const int MAX = 150;

 

int n, m, p;

int a[MAX][MAX];

int color[MAX] = { 0 };

int count = 0;    //方案数量

 

bool Ok(int t) {

for (int i = 1; i <= n; ++i) {

if (a[t][i] == 1 && color[t]== color[i])

return false;

}

return true;

}

 

void Trackback(int t) { //回溯

if (t > n) {

count++;

for (int i = 1; i <= n; i++)

printf("%d ", color[i]);

printf("\n");

}

else {

for (int i = 1; i <= m; i++) {  //颜色小于色数

color[t] = i;

if (Ok(t))

{

Trackback(t + 1);

}

color[t] = 0;

}

}

}

 

int main() {

scanf("%d", &m);

scanf("%d %d", &n, &p);

for (int i = 1; i <= p; ++i) {

int x, y;

scanf("%d %d", &x, &y);

a[x][y] = a[y][x] = 1;

}

Trackback(1);

if (count == 0)

printf("NO\n");

else

printf("%d\n", count);

}

posted on 2021-05-31 16:02  项湫  阅读(132)  评论(0编辑  收藏  举报