3-coloring problem

本文介绍了一种解决图染色问题的方法,通过递归回溯算法为图中每个节点分配颜色,确保相邻节点颜色不同。该算法适用于解决实际场景中的资源分配问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include <Windows.h>

using namespace std;

bool isSafe(const vector<vector<int>> &graph, const vector<int> &color, int v, int c)
{
	for (int i = 0; i != graph.size(); ++i)
		if (graph[v][i] == 1 && color[i] == c)
			return false;
	return true;
}

void printSolution(const vector<int> &color)
{
	cout << "Solution exist: " << endl;
	for (auto a : color)
		cout << a << " ";
}

bool graphColoringUti(const vector<vector<int>> &graph, vector<int> &color,  int v, int m)
{
	if (v == graph.size())
		return true;

	for (int c = 1; c <= m; ++c)
	{
		if (isSafe(graph, color, v, c))
		{
			color[v] = c;

			if (graphColoringUti(graph, color, v + 1, m))
				return true;
			// if assign color c does not lead to a solution, reset it
			color[v] = 0;
		}
	}

	return false;
}

bool graphColoring(const vector<vector<int>> &graph, int m)
{
	vector<int> color(graph.size(), 0);

	if (!graphColoringUti(graph, color, 0, 3))
	{
		cout << "Solution Not Exist";
		return false;
	}

	printSolution(color);
	return true;
}


int main()
{
	vector<vector<int>> graph = { { 0, 1, 1, 1 },
	{ 1, 0, 1, 0 },
	{ 1, 1, 0, 1 },
	{ 1, 0, 1, 0 },
	};
	int m = 3;

	graphColoring(graph, 3);
	cout << endl;
	system("PAUSE");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值