四色原理是什么?网上原理有很多,不懂可以自己搜。
把需要填图的区域看作泰森多边形,每个区域的顶点存储颜色,点之间关系就是TIN三角形,区域和区域的关系就转化为点和点之间的关系。
把所有点储存在邻接表里,着色采用回溯法,原理就是图的遍历。
不懂可以复制下来自己运行一下。
#include
#include
#include
#include
#define MAX_VERTEX_NUM 20
typedef struct ArcNode {
int adjvex;
struct ArcNode *nextarc;
} ArcNode;
typedef struct {
float x;
float y;
} Vertex;
typedef struct VNode {
Vertex data;
ArcNode *firstarc;
int color;
} VNode;
typedef struct{
VNode vertics[MAX_VERTEX_NUM];
int vexnum, arcnum;
} UDGraph;
bool isColorOK(UDGraph, int);
bool getColorPowset(UDGraph &, int, int);
int createUDGraph(UDGraph &);
void outputGraph(UDGraph);
bool isColorOK(UDGraph G, int node)
{
VNode V = G.vertics[node - 1];
ArcNode *T = V.firstarc;
while(T)
{
if(V.color == G.vertics[T->adjvex].color)
return false;
T = T->nextarc;
}
return true;
}
bool getColorPowset(UDGraph &G, int color_Num, int step)
{
if(step > G.vexnum)
return true;
else
{
int i;
for(i=1; i<=color_Num; i++)
{
G.vertics[step - 1].color = i;
if(isColorOK(G, step))
if(getColorPowset(G, color_Num, step + 1))
return true;
G.vertics[step - 1].color = 0;
}
}
return false;
}
int createUDGraph(UDGraph &G)
{
int a, b, i;
ArcNode *p;
printf("请输入结点的个数和边的个数:");
scanf("%d,%d", &(G.vexnum), &(G.arcnum));
getchar();
for(i=0; i
{
G.vertics[i].firstarc =NULL;
G.vertics[i].color = 0;
}
printf("请输入这%d个点之间的拓扑关系:\n", G.vexnum);
for(i=1; i<=G.arcnum; i++)
{
scanf("%d,%d", &a, &b);
getchar();
p = (ArcNode*)malloc(sizeof(ArcNode));
if(!p) exit(-2);
p->adjvex = b - 1;
p->nextarc = G.vertics[a - 1].firstarc;
G.vertics[a - 1].firstarc = p;
p = (ArcNode*)malloc(sizeof(ArcNode));
if(!p) exit(-2);
p->adjvex = a - 1;
p->nextarc = G.vertics[b - 1].firstarc;
G.vertics[b - 1].firstarc = p;
}
return 1;
}
void outputGraph(UDGraph G)
{
int i;
for(i=0; i
printf("结点%d的着色方案为:%d\n", i+1, G.vertics[i].color);
}
int main()
{
UDGraph G;
createUDGraph(G);
if(getColorPowset(G, 4, 1))
{
printf("图形图色成功,为:\n");
outputGraph(G);
}
else
printf("图形图色失败\n");
return 1;
}