我有这个问题:实施两种不同的算法来确定 为无向的每个节点着色所需的最小颜色数 图,以使两个相邻的顶点没有相同的颜色。
我正在尝试使用贪心算法进行操作,问题是,我的程序没有为图形着色,我也不知道为什么,它为所有顶点赋予了第一种颜色。我看不到问题出在哪里。
对于下图,答案应该是: GRAPH
Vertex 0 ---> Color 0
Vertex 1 ---> Color 1
Vertex 2 ---> Color 2
Vertex 3 ---> Color 0
Vertex 4 ---> Color 1
但是我的答案是:
Vertex 0 ---> Color 0
Vertex 1 ---> Color 0
Vertex 2 ---> Color 0
Vertex 3 ---> Color 0
Vertex 4 ---> Color 1
谢谢。
void greedycoloring(struct Graph *graph, int V)
{
int result[V];
result[0] = 0; //assing the color to the first vertex
// initialize the remaining v-1 vertices as uncolored
for(int i = 1; i < V; i++)
result[i] = -1;
// A temporary array to store the available colors. True
// value of av[col] would mean that the color col is
// assigned to one of its adjacent vertices
bool av[V];
for(int col = 0; col < V; col++)
av[col] = true;
// Assign colors to remaining V-1 vertices
for(int u = 1; u < V; u++)
{ struct node* head = graph->adjList[u];
while(head)
{
int iterator = head->vertex;
if(result[iterator] != -1)
av[result[iterator]] = false;
head = head->next;
}// Find the first available color
int col;
for(col = 0; col < V; col++)
if(av[col] == true)
break;
result[u] = col; //assigh the found color
// Reset the values back to true for the next iteration
for(int col = 0; col < V; col++)
av[col] = true;
} int max = 0;
for (int u = 0; u < V; u++)
{
printf("vertex %d ---> color %d\n",u,result[u]);
if(result[u] > max)
max = result[u];
}
printf("chromatic number is %d", max+1);
}