m coloring problem of the (back)

Problem Description

Given undirected graph G and m are different colors. These coloring each vertex of graph G color, the color of each vertex. If this figure is tintable m, to find all the different coloring schemes.

Thinking

m coloring problem is to find a possible allocation scheme satisfies the condition that the color is not the same between adjacent nodes. Use backtracking, for the currently selected node, each cycle distribution of colors m, if the current color is reasonable, that is not the same as with adjacent nodes, to continue to the next recursive, otherwise, "Keep the scene." If the current node recursive larger than the total number of nodes, it can be output, indicating that this is a viable color scheme.

C++

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int n,m;

//记录可能的次数
int cnt=0;
int G[20][20]= {0};
//记录谁涂的啥颜色,0代表没确定
int flag[20]= {0};

//判断是否冲突
bool isok(int c)
{
    for(int k=1; k<=n; k++)
    {
        if(G[c][k]&&flag[c]==flag[k])
        {
            return false;
        }
    }
    return true;
}

void backtrack(int current)
{
    //终止条件
    if(current>n)
    {
        for(int i=1; i<=n; i++)
        {
            cout<<flag[i]<<" ";
        }
        cnt++;
        cout<<endl;
    }
    else
    {
        for(int i=1; i<=m; i++)
        {
            flag[current]=i;
            //剪枝
            if(isok(current))
            {
                backtrack(current+1);
            }
            //保留现场
            flag[current]=0;
        }
    }
}

int main()
{
    int tmp1,tmp2;
    cin>>n>>m;
    while(1)
    {
        cin>>tmp1>>tmp2;
        if(tmp1==0&&tmp2==0)
        {
            break;
        }

        G[tmp1][tmp2]=1;
        G[tmp2][tmp1]=1;
    }

    backtrack(1);
    cout<<cnt;
    return 0;
}

Published 200 original articles · won praise 99 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_43889841/article/details/103362200