#include <stdio.h>
#include <malloc.h>
#define MAPSIZE 10
#define NCOUNTRIES 5
struct node{ /* 结点类型*/
int Country;
struct node *next;
};
struct{
struct node *head;
struct node *rear;
}Countries[NCOUNTRIES]; /*保存临国关系*/
void main()
{
int Map[100][100]=
{
{1,1,1,1,1,1,1,1,1,1},
{1,1,1,2,2,2,2,1,1,1},
{1,1,2,2,3,2,2,2,2,1},
{1,1,2,3,3,3,3,3,1,1},
{1,2,2,2,5,4,4,4,4,1},
{1,1,1,5,5,5,5,5,5,1},
{1,1,5,5,5,5,5,5,1,1},
{1,1,5,5,5,5,5,1,1,1},
{1,1,0,0,5,5,5,1,1,1},
{1,1,1,1,1,1,1,1,1,1}
};
int Color[NCOUNTRIES],i,j;
void SetColor(const int Map[100][100], const int MapSize,
const int nCountries, int Color[]); /*原型申明*/
if (NCOUNTRIES>10)
{
printf("国家数目不能超过10个/n!");
return;
}
for(i=0;i<MAPSIZE;i++) /*初始化MAP*/
for(j=MAPSIZE;j<100;j++)
Map[j]=0;
for(i=MAPSIZE;i<100;i++) /*初始化MAP*/
for(j=0;j<100;j++)
Map[j]=0;
for(i=0;i<NCOUNTRIES;i++) /*初始化Color和Countries*/
{
Color=0;
Countries.head=(struct node *)malloc(sizeof(struct node));
Countries.head->Country=i+1;
Countries.head->next=NULL;
Countries.rear=Countries.head;
}
SetColor(Map,MAPSIZE,NCOUNTRIES,Color);
printf("/n着色方案如下:/n");
for(i=0;i<NCOUNTRIES;i++)
printf("国家%d: 颜色%d/n",i+1,Color);
}
void SetColor(const int Map[100][100], const int MapSize,
const int nCountries, int Color[])
{
int i=0;
struct node *p;
void CreateGraph(const int Map[100][100]); /*原型申明*/
CreateGraph(Map);
printf("临国关系图如下:/n"); /*打印临国关系*/
for(i=0;i<nCountries;i++) /*调试时使用*/
{
for(p=Countries.head;p!=NULL;p=p->next)
printf("%d->",p->Country );
printf("^/n");
}i=0;
while(i<nCountries) /*给国家着色*/
{
Color++;
for(p=Countries.head->next;p!=NULL;p=p->next )
if(Color[p->Country-1]==Color) break;
if(p==NULL)
i++;
else if(Color==4)
Color=0;
}
}
void CreateGraph(const int Map[100][100]) /*创建临国关系图*/
{
int i,j;
void Check(const int Map[100][100],int i,int j); /*原型申明*/
for(i=0;i<MAPSIZE;i++)
for(j=0;j<MAPSIZE;j++)
Check(Map,i,j);
}
void Check(const int Map[100][100],int i,int j) /*检测结点与四周点是否同国*/
{
void SetGraph(const int Map[100][100],int a,int b,int i,int j); /*原型申明*/
if(Map[j]==0) return;
if(i<MAPSIZE-1 && Map[j]!=0 && Map[j]!=Map[j]) /*检测结点与其右结点是否同国*/
SetGraph(Map,i+1,j,i,j);
if(j<MAPSIZE-1 && Map[j+1]!=0 && Map[j+1]!=Map[j]) /*检测结点与其下结点是否同国*/
SetGraph(Map,i,j+1,i,j);
/*由于是无向图,所以省去检测左、上结点*/
}
void SetGraph(const int Map[100][100],int a,int b,int i,int j) /*添加临国关系到图中*/
{
struct node *p;
for(p=Countries[Map[a]-1].head->next;p!=NULL;p=p->next) /*检测临国关系是否添加*/
if(p->Country==Map[j]) break;
if(p==NULL) /*添加临国关系*/
{
Countries[Map[a]-1].rear->next=(struct node *)malloc(sizeof(struct node));
Countries[Map[a]-1].rear=Countries[Map[a]-1].rear->next;
Countries[Map[a]-1].rear->Country=Map[j];
Countries[Map[a]-1].rear->next=NULL;
Countries[Map[j]-1].rear->next=(struct node *)malloc(sizeof(struct node));
Countries[Map[j]-1].rear=Countries[Map[j]-1].rear->next;
Countries[Map[j]-1].rear->Country=Map[a];
Countries[Map[j]-1].rear->next=NULL;
}
}
四色着图
最新推荐文章于 2021-05-17 13:08:32 发布