BG12

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

2.解析
与“N皇后问题”一样。在填写每一个顶点的颜色时检查与相邻已填顶点的颜色是否相同。如果不同,则填上;如果相同(冲突),则另选一种;如果已没有颜色可供选择,则回溯到上一顶点。重复这一过程,直到所有顶点的颜色都已填上。
在这里插入图片描述

  1. 设计
    在这里插入图片描述

#include<iostream>
using namespace std;
#define MAX 100
int color[MAX];
int graph[MAX][MAX] = { 0 };
int n, m;
int cnt = 0;
bool isDiffColor(int index) {
	for (int i = 0; i < n; i++) {
		if (graph[index][i] == 1 && color[index] == color[i]) {
			return false;
		}
	}
	return true;
}
void backTracking(int index) {

	if (index == n) {
		for (int i = 0; i < n; i++) {
			cout << color[i] << " ";
		}
		cnt++;
		cout << endl;
	}
	else {
		for (int j = 1; j <= m; j++) {
			color[index] = j;
			if (isDiffColor(index)) { 
				backTracking(index + 1);
			}
			color[index] = 0;
		}
	}
}
int main() {
	cout << "请输入顶点数n和颜色数m:" ;
	cin >> n >> m;
	cout << "请输入无向连通图:" << endl;
	for (int i = 0; i < n; i++) 
		for (int j = 0; j < n; j++) 
			cin >> graph[i][j];
	cout << "Answer:" << endl;
	backTracking(0);
	if (cnt == 0) {
		cout << "No" << endl;
	}
	else {
		cout << "可能的着色方案有:" << cnt << "种" << endl;
	}
}

时间复杂度:T=O(nm^n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值