0% found this document useful (0 votes)
12 views

Assignment 14 Graph Coloring Problem

The document presents an implementation of the Graph Coloring Problem using a greedy algorithm in C. It includes a function to assign colors to vertices based on their adjacency and prints the assigned colors. A sample undirected graph is provided, demonstrating the algorithm's functionality.

Uploaded by

roysayanccp05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Assignment 14 Graph Coloring Problem

The document presents an implementation of the Graph Coloring Problem using a greedy algorithm in C. It includes a function to assign colors to vertices based on their adjacency and prints the assigned colors. A sample undirected graph is provided, demonstrating the algorithm's functionality.

Uploaded by

roysayanccp05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like