#include<stdio.h>
#include<stdlib.h>
struct stack{
int *data;
int top;
int maxSize;
};
struct stack *createStack(int maxsize){
struct stack *s;
s=(struct stack *)malloc(sizeof(struct stack));
s->data=(int *)malloc(sizeof(int)*maxsize);
s->top=-1;
s->maxSize=maxsize;
return s;
}
int isFull(struct stack *s){
return s->top==s->maxSize-1;
}
int isEmpty(struct stack *s){
return s->top==-1;
}
void push(struct stack *s,int num){
if(isFull(s)){
printf("stack is full\n");
return;
}
s->data[++s->top]=num;
}
int pop(struct stack *s){
if(isEmpty(s)){
printf("stack is empty\n");
exit(-1);
}
return s->data[s->top--];
}
int collition(int map[6][6],struct stack *s){/*判断冲突*/
for(int i=0;i<s->top;i++){
if(map[i][s->top]==1&&s->data[i]==s->data[s->top]){
return 1;
}
}
return 0;
}
int main(){
struct stack *s;
int n=6;
s=createStack(n);
char *Color[4]={"red","yellow","blue","green"};
int map[6][6]={
0,1,1,1,1,1,
1,0,1,0,1,0,
1,1,0,1,1,1,
1,0,1,0,0,1,
1,1,1,0,0,1,
1,0,1,1,1,0
};
int color=0;
push(s,color);
while(s->top<5){
while(color<4&&s->top<5){
push(s,color);
while(collition(map,s)){/*冲突就退栈后将下一种颜色入栈*/
pop(s);
color++;
push(s,color);
}
if(color<4){/*此时color<4说明之前的颜色分配成功,将color置为零为下次分配颜色做准备*/
color=0;
}
}
if(color>=4){/*color>=4说明颜色分配不成功,退栈回溯到上一节点,用下一个color继续压栈尝试新的分配*/
color=pop(s)+1;
}
}
for(int j=0;j<6;j++){
printf("%s\n",Color[s->data[j]]);
}
return 0;
}
C语言实现利用栈解决四色定理着色问题
最新推荐文章于 2022-08-11 06:23:21 发布