题意:使用四种颜色对N块区域涂色,输出所有涂色方案
使用图的遍历来做,每块区域抽象为图顶点,四种颜色,回溯遍历涂色,代码如下(使用文件读取数据):
#include <stdio.h>
#include<stdlib.h>
#define DEBUG
#define MAXVEX 100 //最大顶点数
typedef struct ArcNode//边表结点
{
int adjvex;//邻接点域,存储该顶点对应的下标
int weight;//用于存储权值,对于非网图可以不需要
struct ArcNode *nextarc; //链域,指向下一个邻接点
} ArcNode;
typedef struct VNode//顶点表结点
{
int data;//顶点域,存储顶点信息
ArcNode *firstarc;//边表头指针
int color;
} VNode, AdjList[MAXVEX];
typedef struct
{
AdjList adjList;
int numNodes, numEdges; // 图中当前顶点数和边数
} GraphAdjList;
void CreateALGraph(GraphAdjList *Gp)
{
int i, j, k;
ArcNode *pe;
FILE *fp;
fp=fopen("1.txt","r");
fscanf(fp,"%d %d",&Gp->numNodes,&Gp->numEdges);
printf("顶点数与边数:%d %d\n",Gp->numNodes,Gp->numEdges);
for (i = 0 ; i < Gp->numNodes; i++)
{
fscanf(fp,"%d",&Gp->adjList[i].data);
printf("已输入顶点%d信息:%d\n",i,Gp->adjList[i].data);
Gp->adjList[i].firstarc = NULL;//将边表置为空表
Gp->adjList[i].color=0;
}
for (k = 0; k < Gp->numEdges; k++)//建立边表
{
fscanf(fp,"%d %d",&i,&j);
printf("已初始化输入边(%d,%d)\n",i,j);
pe = (ArcNode*)malloc(sizeof(ArcNode));
pe->adjvex = j;//邻接序号为j
//将pe的指针指向当前顶点上指向的结点
pe->nextarc =Gp->adjList[i].firstarc;
Gp->adjList[i].firstarc = pe;//将当前顶点的指针指向pe
pe = (ArcNode*)malloc(sizeof(ArcNode));
pe->adjvex = i;
pe->nextarc =Gp->adjList[j].firstarc;
Gp->adjList[j].firstarc = pe;
}
}
int cheak(GraphAdjList *G,int step)///看看相邻顶点是否有重复的,有就不能要这个颜色
{
ArcNode *p=G->adjList[step].firstarc;
while(p!=NULL)
{
if(G->adjList[p->adjvex].color==G->adjList[step].color)
{
return 0;
}
p=p->nextarc;
}
return 1;
}
void f(GraphAdjList *G,int step)
{
if(step==G->numNodes-1)///点遍历完了那么就要输出
{
int i;
printf("一组符合的:\n");
for(i=0; i<G->numNodes; i++)
{
printf("%d点涂:%d ",i,G->adjList[i].color);
printf("\n");
}
printf("\n");
}
else
{
int i=0;
for(i=1; i<=4; i++)
{
G->adjList[step].color=i;
if(cheak(G,step))///看看相邻顶点是否有重复的,有就不能要这个颜色
{
f(G,step+1);
}
}
}
}
int t=0;
void f2(GraphAdjList *G,int step)
{
ArcNode *p=G->adjList[step].firstarc;
while(p!=NULL)
{
t++;
printf("%d ",p->adjvex);
p=p->nextarc;
}
printf("\nt=%d",t);
}
int main()
{
GraphAdjList G;
CreateALGraph(&G);
f(&G,0);
return 0;
}