C语言实现利用栈解决四色定理着色问题

#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;
}

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值