地图四染色

数据结构书上的。。。

依旧回溯

#include <iostream>
#include <string.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int num;  // 区域数量
int arr[100][100];  // 区域颜色邻接矩阵 
int stack[100];  // 数组模拟栈
int top = -1;  // 指针 

bool canuse(int area, int color)
{
	int i = 0;
	do
	{
		if(arr[area][i] == 1 && stack[i] == color) 
			return false;
		i++;
	} while(i <= top);
	return true;
}

// 地图四染色 
int main(int argc, char *argv[]) {
	cin>>num;
	memset(arr, 0, sizeof(int) * 10000);
	// 输入邻接矩阵,(深入理解计算机系统162页,且这样试试吧) 
	int *row = &arr[0][0];
	int j = 0; 
	do
	{
		int i = 0;
		do
		{
			cin>>row[i];
			i++;
		}while(i < num);
		row += 100;
		j++;
	}while(j < num);

	// 回溯求解
	int trying = 0;
	do
	{
		while( top < num - 1 && canuse(top + 1, trying) && trying < 4)
		{
			top++;
			stack[top] = trying;
			trying = 0; 
		}
		if(top == num - 1)
		{
			for(int i = 0 ; i < num; i++)
			{
				cout<<stack[i]<<" ";
			}
			cout<<endl;
			trying = stack[top] + 1;
			top--;
		}
		else if( trying >= 4)
		{
			trying = stack[top] + 1;
			top--;
		}
		else
		{
			trying++;
		}
	}while(top != -1 || trying != 4);
	return 0;
}

  

转载于:https://www.cnblogs.com/coralyms/p/4367115.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值