Graph coloring problem (backtracking method)

Problem:
Given an undirected connected graph G=(V,E) and c different colors, use these colors to color the vertices of the graph G, and each vertex is colored. If a graph requires at least c colors to make the two vertices connected by each edge of the graph have different colors, then c is called the chromatic number of the graph. 
The famous four-color theorem means that every flat map can be colored with only four colors, and no two adjacent areas have the same color.

Find: Given the vertex v of the graph, the edge adjacency relationship between the vertices c[][], the number of colors c, how many coloring methods are there?

 

This is a very typical backtracking problem. The solution is the same as the "Eight Queens Problem". When filling in the color of each vertex, check whether the color of the adjacent vertex is the same. If they are different, fill in; if they are the same (conflict), choose another one; if there is no color to choose from, go back to the previous vertex. Repeat this process until the colors of all the vertices are filled.

 

input
5 4 
0 1 1 1 0 
1 0 1 1 1 
1 1 0 1 0 
1 1 1 0 1 
0 1 0 1 0

output 
48

 

 

è¿éåå¾çæè¿ °

For the above figure, the number of colors is 4 and the number of vertices is 5. The solution tree obtained is as follows:

è¿éåå¾çæè¿ °

 

#include<iostream>
using namespace std;
int c[100][100]; //邻接矩阵
int color[100];  //记录每个顶点的颜色 
int count,m,n; //count记录方案数 n个顶点 m种颜色 
int Check(int k)    //检查第i个顶点的颜色是否满足条件 
{
	for(int i=1;i<=k;i++)
		{
			if(c[k][i]==1&&color[i]==color[k]) //k与i之间相连并且i顶点的颜色与k顶点的颜色相同 
			return 0;	
		}	
	return 1;	
} 

void GraphColor(int step)  
{
	if(step==n+1)  //表示前面所有的顶点颜色都已经填完 
	{
		for(int i=1;i<=n;i++)
			printf("%d ",color[i]);
		count++;
		printf("\n");
		return ;
	}
	else
	{
		for(int i=1;i<=m;i++)
		{
			color[step]=i;   //首先将这个顶点颜色换为i 
			if(Check(step)==1)  //检查是否符合条件 
			{
				GraphColor(step+1); //符合条件则走下一步 
			 
			}		
			color[step]=0;  //回溯 置为0 
		}
	}
}

int main(void)
{
	int a,b;
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
		{
				cin>>c[i][j];
		}
 
	GraphColor(1);
	printf("%d",count);
	return 0;	
}

 

 

Guess you like

Origin blog.csdn.net/a447332241/article/details/87819537