图的m着色(回溯法)

//
//Description:图的m着色问题(回溯法)
//
#include <iostream>
using namespace std;

int n;//图的顶点个数
int m;//可用颜色数
int a[21][21];//程序中使用时从下标1开始;程序中用于存储图的邻接矩阵
int x[20];//用于存储当前解
static  long sum;//当前已找到的可m着色方案数

bool ok(int k)
{
	for (int j = 1; j <= n; j++)
	{
		if (a[k][j] && (x[j] == x[k]))
			return 0;
	}
	return 1;
}

void backtrack(int t)
{
	if (t>n)
	{
		sum++;
		cout << "        第" << sum << "种解决方案为 :\n";
		for (int i = 1; i <= n; i++)
		{
			cout << x[i] << " ";
		}
		cout << endl;
	}
	else
	{
		for (int i = 1; i <= m; i++)
		{
			x[t] = i;
			if (ok(t))
			{
				backtrack(t + 1);
			}
			x[t] = 0;
		}
	}
}


long mColoring(int mm)
{
	m = mm;
	sum = 0;
	backtrack(1);
	return sum;
}

void inputRenc(int  p[21][21])
{
	for (int i = 1; i <= n; i++)
	{
		for (int j = i + 1; j <= n; j++)  //**分析为什么如邻接矩阵中[1][1]为1???
		{
			cout << "请输图的邻接矩阵中[" << i << "][" << j << "]的值" << endl;
			cin >> p[i][j];
			p[j][i] = p[i][j];
		}
		cout << endl;
	}
}

void  outputRenc(int  p[21][21])
{
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			cout << p[i][j] << ' ';
		}
		cout << endl;
	}

}
void main()
{
	cout << "\n\t==========图的m着色问题============\n";
	cout << "Please enter the number of points and colors :\n";
	cin >> n >> m;
	cout << "\n==========(输入)图的邻接矩阵\n";
	inputRenc(a);
	cout << "\n==========(输出)图的邻接矩阵\n";
	outputRenc(a);
	cout << "\n==========判断可着色性\n";
	mColoring(m);
	if (sum == 0)
		cout << "  无可行方案!" << endl;
	cout << "-------------------------------------------------------------------------------" << endl;
	cout << n << " 个顶点" << "按所给的邻接关系着 " << m << " 种颜色,总的着色方案有 " << sum << " 个\n";

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值