图着色问题可以分为两种:
1、判定m中颜色是否可以为一个图的每个顶点进行着色,使得相邻(之间右边)的两个顶点颜色不能相同,这类图着色问题称作判定图着色。
2、给定一个图,对它的顶点进行着色,使得相邻的两个顶点颜色不能相同,求最少可以用几种颜色对图进行着色,并满足要求。
1、第一类图着色问题解法(此处暂列,等学习了更好的方法,更新还会):
可以通过回溯法进行判定:对所有顶点枚举所有可能颜色。
如下C语言程序可供参考
#include<stdio.h>
#include<stdlib.h>
//用邻接表表示图
typedef struct
child_node
//连接表中,一个图节点的邻接节点的数据结构
{
int node_num;
struct child_node* next_child;
}child_node;
typedef struct graph_node
//图节点的数据结构
{
int node_num;
struct graph_node* next_node;
child_node* first_child;
}graph_node;
int isok(graph_node* first_node,int step,int* colors)
{
int i;
graph_node* node_step=first_node;
while(node_step->node_num!=step)
//找到编号为step的图节点
{
node_step=node_step->next_node;
}
child_node*
child_of_step=node_step->first_child;
while(child_of_step!=NULL)
//遍历编号为step的图节点的邻接点
{
//编号小于step的colors值才有效,所以在if语句中加入了对节点编号的判断
if((child_of_step->node_num<step)&&(colors[step]==colors[child_of_step->node_num]))
return 0;
child_of_step=child_of_step->next_child;
}
return 1;
}
int DFS(graph_node* first_node,int node_nums,int step,int*
colors,int color_num)
{
if(step>=node_nums)
//表示回溯法进行到了最后一个图节点
return 1;
int i=0;
for(i=0;i<color_num;i++)
//对所有颜色进行枚举
{
colors[step]=i;
if(isok(first_node,step,colors))
{
if(DFS(first_node,node_nums,step+1,colors,color_num))
//回溯法往下递归
return 1;
}
colors[step]=0; //回溯失败,返回时做的处理
}
return 0;
}
void init_graph(graph_node** p_first_node_of_the_graph,int
node_nums,int edge_nums)
{
int i;
for(i=0;i<node_nums;i++)
//创建图节点
{
if(i==0)
{
*p_first_node_of_the_graph=(graph_node*)malloc(sizeof(graph_node));
(*p_first_node_of_the_graph)->next_node=NULL;
(*p_first_node_of_the_graph)->first_child=NULL;
(*p_first_node_of_the_graph)->node_num=i;
}
else
{
graph_node* temp=*p_first_node_of_the_graph;
while(temp->next_node!=NULL)