0% found this document useful (0 votes)
6 views2 pages

Graph Coloring

The document contains a C program that implements a graph coloring algorithm using backtracking. It allows the user to input the number of vertices, edges, and colors, and checks if the graph can be colored with the given number of colors without adjacent vertices sharing the same color. If a valid coloring is found, it outputs the color assignment; otherwise, it indicates that no solution exists.

Uploaded by

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

Graph Coloring

The document contains a C program that implements a graph coloring algorithm using backtracking. It allows the user to input the number of vertices, edges, and colors, and checks if the graph can be colored with the given number of colors without adjacent vertices sharing the same color. If a valid coloring is found, it outputs the color assignment; otherwise, it indicates that no solution exists.

Uploaded by

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

#include <stdio.

h>
#include <stdbool.h>

#define MAX 100

int graph[MAX][MAX];
int color[MAX];
int V; // Number of vertices
int m; // Number of colors

// Function to check if current color assignment is safe


bool isSafe(int v, int c) {
for (int i = 0; i < V; i++) {
if (graph[v][i] && color[i] == c)
return false;
}
return true;
}

// Backtracking function to assign colors


bool graphColoring(int v) {
if (v == V)
return true;

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


if (isSafe(v, c)) {
color[v] = c;

if (graphColoring(v + 1))
return true;

color[v] = 0; // Backtrack
}
}
return false;
}

int main() {
int E; // Number of edges
printf("Enter number of vertices: ");
scanf("%d", &V);

printf("Enter number of edges: ");


scanf("%d", &E);

// Initialize graph with 0s


for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = 0;
printf("Enter edges (format: u v) [0-based indexing]:\n");
for (int i = 0; i < E; i++) {
int u, v;
scanf("%d %d", &u, &v);
graph[u][v] = 1;
graph[v][u] = 1; // Since undirected
}

printf("Enter number of colors: ");


scanf("%d", &m);

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


color[i] = 0;

if (graphColoring(0)) {
printf("Color assignment to vertices:\n");
for (int i = 0; i < V; i++)
printf("Vertex %d ---> Color %d\n", i, color[i]);
} else {
printf("Solution does not exist with %d colors.\n", m);
}

return 0;
}

You might also like