图染色计算机背景,图着色算法详解(Graph Coloring)

给定无向连通图和m种不一样的颜色。用这些颜色为图G的各顶点着色,每一个顶点着一种颜色。是否有一种着色法使G中每条边的两个顶点有不一样的颜色。算法

这个问题是图的m可着色断定问题。若一个图最少须要m种颜色才能使图中每条边相链接的两个顶点着不一样颜色,称这个数m为这个图的色数。数组

求一个图的色数m称为图的m可着色优化问题。 给定一个图以及m种颜色,请计算出涂色方案数。函数

a93812cd7c1a42959a094837.html

分析:

细致分析后,t表明顶点仍是能分析出来的。

使用到了邻接矩阵

还有就是color数组,也是解题的关键,要明确color数组表明的含义:color[n],大小为n,下标确定表明顶点,里面的值表明这个顶点放的是哪一种颜色。

Traceback(t)的t表明某一个顶点,这个顶点具体放哪一种颜色不知道,确定有个for循环从第一种颜色到最后一种颜色都要试一下,那么color[t]里就放当前这种颜色。OK(t)判断一下,若是能够,traceback(t+1)。

OK(t)中,t顶点和哪些顶点有联系,我就去判断这些点放置的颜色有没有和我相同,如有相同的,return false;不然,return true。优化

#include

#include

#define V 4//图中的顶点数

/* 打印解决方案的实用函数 */

void printSolution(int color[])

{

printf(" Following are the assigned colors \n");

for (int i = 0; i < V; i++)

printf(" %d ", color[i]);

printf("\n");

}

bool isSafe(int v, bool graph[V][V], int color[], int c)用于检查当前颜色分配的实用程序函数

{

for (int i = 0; i < V; i++)

if (graph[v][i] && c == color[i])

return false;

return true;

}

void graphColoring(bool graph[V][V], int m, int color[], int v)//求解m着色问题的递推效用函数

{

if (v == V)//基本状况:若是全部顶点都指定了颜色,则返回真

{

printSolution(color);

return;

}

/* 考虑这个顶点v并尝试不一样的颜色*/

for (int c = 1; c <= m; c++)

{

/* 检查颜色C到V的分配是否正确*/

if (isSafe(v, graph, color, c))

{

color[v] = c;

/* 递归为其他顶点指定颜色 */

graphColoring(graph, m, color, v + 1);

/* 若是指定颜色C不会致使解决方案而后删除它 */

color[v] = 0;

}

}

}

// driver program to test above function

int main()

{

/* Create following graph and test whether it is 3 colorable

(3)---(2)

| / |

| / |

| / |

(0)---(1)

*/

bool graph[V][V] = { { 0, 1, 1, 1 },

{ 1, 0, 1, 0 },

{ 1, 1, 0, 1 },

{ 1, 0, 1, 0 },

};

int m = 3; // Number of colors

int color[V];

for (int i = 0; i < V; i++)

color[i] = 0;

graphColoring(graph, m, color, 0);

system("pause");

return 0;

}

运行结果:spa

343d552e598b630f7104ec233aa1cf90.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值