首页 > 其他 > 详细

地图四染色

时间:2015-03-25 23:08:29      阅读:162      评论:0      收藏:0      [点我收藏+]

数据结构书上的。。。

依旧回溯

#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;
}

  

地图四染色

原文:http://www.cnblogs.com/coralyms/p/4367115.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!