Assignment – 14
To implement and solve the Graph Coloring Problem using a greedy algorithm.
Code:
#include <stdio.h>
#include <stdbool.h>
#define V 5 // Number of vertices in the graph
// Function to print the colors assigned to vertices
void printColors(int color[]) {
printf("Vertex\tColor\n");
for (int i = 0; i < V; i++) {
printf("%d\t%d\n", i, color[i]);
}
}
// Function to assign colors using Greedy algorithm
void greedyColoring(int graph[V][V]) {
int color[V]; // Color assigned to each vertex
color[0] = 0; // First vertex is always colored with 0
// Initialize all other vertices as unassigned (-1)
for (int i = 1; i < V; i++)
color[i] = -1;
bool available[V]; // Keep track of available colors
for (int u = 1; u < V; u++) {
// Initially, all colors are available
for (int i = 0; i < V; i++)
available[i] = true;
// Check colors of adjacent vertices and mark them unavailable
for (int i = 0; i < V; i++) {
if (graph[u][i] && color[i] != -1)
available[color[i]] = false;
}
// Find the first available color
for (int c = 0; c < V; c++) {
if (available[c]) {
color[u] = c;
break;
}
}
}
// Print result
printColors(color);
}
// Sample graph and main function
int main() {
/* Example graph (Undirected)
Adjacency matrix representation
(0)---(1)
| /|
| / |
(2)---(3)
|
(4)
*/
int graph[V][V] = {
{0, 1, 1, 0, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 1, 1},
{0, 1, 1, 0, 0},
{0, 0, 1, 0, 0}
};
greedyColoring(graph);
return 0;
}
Output:
Vertex Color
0 0
1 1
2 2
3 0
4 0