三着色问题

算法代码

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
const int N=5;
int c[N+1]={0,};
int map[N+1][N+1]={
	{0,0,0,0,0,0},
	{0,0,1,1,0,0},
	{0,1,0,0,1,1},
	{0,1,0,0,1,1},
	{0,0,1,1,0,1},	
	{0,0,1,1,1,0}
};

void display()
{
	printf("         %d         \n",c[1]);
	printf("       *    *     \n");
    printf("     *        *   \n");
	printf("   *            *     \n");
	printf("  %d              %d\n",c[2],c[3]);
	printf("  * *          * *     \n");    
	printf("  *   *      *   *   \n");	
	printf("  *     *  *     *     \n");
	printf("  *     *  *     *   \n");
	printf("  *  *        *  *    \n");
	printf("  %d * * * *  *   %d \n",c[4],c[5]);
	printf("                 \n");
	printf("\n");	
}
bool iscolor(int c[],int k)	
{
	for(int i=1,sum=0;i<=N&&i!=k;i++)
		if(map[k][i]&&c[i]==c[k])
			return false;
		return true;
}
int GraphColorRec(int k)
{
	for(int color=1;color<=3;color++) 
	{
	 	c[k]=color;
	  	if(iscolor(c,k))		//部分解或解
		{
	     	if(k<N) 					//部分解
		     	GraphColorRec(k+1); 	//进入下一个结点
	     	else			 				//是解
		      	display();
		}
	}
	c[k]=0;
	return 0;
}
int GraphColor()
{
	int k=1;		//k表示当前处理的结点号
	while (k>0)	 	//k=0表示无法后退,程序终止。
	{
		while (c[k]<3)	       		//最多三种着色
		{
			c[k]=c[k]+1;			//下一种颜色
			if (iscolor(c,k))	//部分解或解
			{
				if (k==N) 		//完全解
					display();
		        else	 		//部分解
					k++;		//前进(下一个结点)
			}
		}
		c[k--]=0 ;			//清0后回溯
	}
	return 0;
}
int main()
{
	//GraphColorRec(1);
	GraphColor();
	printf("\n");
	return 0;
}

测试结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39464369/article/details/88555491