图的m涂色问题(回溯法)

这个博客展示了如何使用C++实现一个图的着色问题解决方案,通过回溯法来寻找所有可能的染色方案。程序首先定义了一个Color类,包含邻接矩阵、当前解和解的数量等成员,接着利用递归回溯法进行染色判断和搜索。在OK函数中检查相邻节点的颜色冲突,最后输出所有可行的解及其总数。
摘要由CSDN通过智能技术生成
#include<bits/stdc++.h>
using namespace std;
class Color{
private:
    int n_;//顶点数
    int m_;//颜色数
    int **Martix;//邻接矩阵
    int *x;      //当前解
    int solution_num_;    //解的个数
    bool OK(int k);       //判断第k个涂色是否与前边的涂色冲突
    void Backtrack(int t);//递归回溯
    void Print();
public:
    Color(int n,int edgenum,int m):n_(n),m_(m){
       solution_num_ = 0;
       x = new int[n_+ 1];
       for(int i=1;i<=n_;i++){
        x[i] = 0;
       }
       //new一个二维数组初始化
       Martix = new int*[n_+ 1];
       for(int i=0;i<n_+ 1;i++){
         Martix[i] = new int [n_+ 1];
       }
       //二维数组初始化
       for(int i=1;i<=n_;i++)
         for(int j=1;j<=n_;j++)
            Martix[i][j] = -1;
       //输入边
       cout<<"input edges"<<endl;
       for(int i=0;i<edgenum;i++){
         int s,e;
         cin>>s>>e;
         Martix[s][e] = 1;
       }
       cout<<"solution is"<<endl;
       Backtrack(1);               //调用函数
       Print();
}
   ~Color(){
       delete [] x;
       delete [] Martix;
   }
};
void Color::Backtrack(int t){
    if(t>n_){                       //如果找到一个解就把对应的解输出,solution_num_++;
        solution_num_++;
        for(int i=1;i<=n_;i++){
            cout<<x[i]<<" ";
        }
        cout<<endl;
    }
    else{                           //如果还没有到达根节点
        for(int i=1;i<=m_;i++){
            x[t] = i;
            if(OK(t)){              //如果此涂色合法则搜索下一层节点
                Backtrack(t+1);
            }
        }
    }

}
bool Color::OK(int k){
    for(int i=1;i<k;i++){
        if(x[i]==x[k] && Martix[i][k]==1)
            return false;
    }
    return true;
}
void Color::Print(){
    cout<<"sum_solution is "<<solution_num_<<endl;
}
int main(){
    int vertexnum,m,edgenum;
    cout<<"input numbers of vertex and edge and color"<<endl;
    cin>>vertexnum>>edgenum>>m;
    Color color(vertexnum,edgenum,m);
    return 0;
}
//7 11 3
//1 2
//1 6
//1 7
//2 3
//2 7
//3 4
//3 7
//4 5
//4 6
//5 6
//6 7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值