回溯法——图m染色问题

给定无向连通图G和m种颜色,要求用这些颜色给定点着色要求,每个顶点颜色和相邻顶点不相同。

算法思想:依次对每个点尝试着色,如果颜色重复就换下一个颜色。

#include<iostream>
#include<vector>
using namespace std;
//给定无向连通图G和m种颜色,要求用这些颜色给定点着色要求,每个顶点颜色和相邻顶点不相同。
vector<vector<int>> c(4, vector<int>(4, 0));//图
vector<int> color(4,0);//第i个顶点的颜色

//判断相邻顶点颜色是否重复
bool same(vector<vector<int>> c, int v, vector<int> color) {
	for (int i = 0; i < c[0].size(); i++) {
		if (c[v][i] == 1) {
			if (color[v] == color[i]) {
				return true;
			}
		}
	}
	return false;
}
//算法思想:依次对每个点尝试着色,如果颜色重复就换下一个颜色
void dfs(int k,vector<vector<int>> c, vector<int> color, int m) {//第k个顶点,总共m种颜色,color为染色结果,c为邻接表
	if (k==4) {
		for (auto it : color) {
			cout << it << " ";
		}
		cout << endl;
	}
	else {	
			for (int j = 1; j <= m; j++) {
				color[k]=j;
				if (!same(c,k,color)) {
					dfs(k + 1, c, color, m);
				}
			}		
	}
}
int main() {
	c[0][1] = 1;
	c[1][0] = 1;
	c[1][2] = 1;
	c[2][1] = 1;
	c[2][3] = 1;
	c[3][2] = 1;
	c[3][0] = 1;
	c[0][3] = 1;//对边进行初始化
	dfs(0, c, color, 5);
	//for (auto it : color) {
	//	cout << it << " ";
	//}
}

给定无向连通图G,要求每个顶点颜色和相邻顶点不相同,求最少要用多少种颜色。

算法思想:每次尝试n种颜色,去着色,1<n<顶点个数,如果能给所有顶点上色则输出n。

#include<iostream>
#include<vector>
using namespace std;
//给定无向连通图G和m种颜色,要求用这些颜色给定点着色要求,每个顶点颜色和相邻顶点不相同。
vector<vector<int>> c(4, vector<int>(4, 0));//图
vector<int> color(4,0);//第i个顶点的颜色

//判断相邻顶点颜色是否重复
bool same(vector<vector<int>> c, int v, vector<int> color) {
	for (int i = 0; i < c[0].size(); i++) {
		if (c[v][i] == 1) {
			if (color[v] == color[i]) {
				return true;
			}
		}
	}
	return false;
}
bool solved = false;
//算法思想:依次对每个点尝试着色,如果颜色重复就换下一个颜色
void dfs(int k,vector<vector<int>> c, vector<int> color, int m) {//第k个顶点,总共m种颜色,color为染色结果,c为邻接表
	if (k==4) {
		//for (auto it : color) {
		//	cout << it << " ";
		//}
		//cout << endl;
		solved = true;
	}
	else {	
			for (int j = 1; j <= m; j++) {
				color[k]=j;
				if (!same(c,k,color)) {
					dfs(k + 1, c, color, m);
				}
			}		
	}
}


int main() {
	c[0][1] = 1;
	c[1][0] = 1;
	c[1][2] = 1;
	c[2][1] = 1;
	c[2][3] = 1;
	c[3][2] = 1;
	c[3][0] = 1;
	c[0][3] = 1;//对边进行初始化
	for (int i = 1; i < 5; i++) {
		dfs(0, c, color, i);
		if (solved) {
			cout << i << endl;
			break;
		}
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值