算法代码
#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;
while (k>0)
{
while (c[k]<3)
{
c[k]=c[k]+1;
if (iscolor(c,k))
{
if (k==N)
display();
else
k++;
}
}
c[k--]=0 ;
}
return 0;
}
int main()
{
GraphColor();
printf("\n");
return 0;
}
测试结果