Skip to content

Commit 44e114b

Browse files
committed
Added a program for m_coloring problem in graph
1 parent 546e883 commit 44e114b

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Graph/Graph_m_Coloring/m_color.cpp

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
# define V 5
5+
6+
void printSolution(int color[]);
7+
8+
bool isSafe (int v, int graph[V][V], int color[], int c)
9+
{
10+
for (int i = 0; i < V; i++)
11+
{
12+
if (graph[v][i] && c == color[i])
13+
return false;
14+
}
15+
return true;
16+
}
17+
18+
19+
bool graphColoringUtil(int graph[V][V], int m, int color[], int v)
20+
{
21+
if (v == V)
22+
return true;
23+
24+
25+
for (int c = 1; c <= m; c++)
26+
{
27+
28+
if (isSafe(v, graph, color, c))
29+
{
30+
color[v] = c;
31+
if (graphColoringUtil (graph, m, color, v+1) == true)
32+
return true;
33+
34+
color[v] = 0;
35+
}
36+
}
37+
38+
return false;
39+
}
40+
41+
bool graphColoring(int graph[V][V], int m)
42+
{
43+
int *color = new int[V];
44+
for (int i = 0; i < V; i++)
45+
color[i] = 0;
46+
47+
if (graphColoringUtil(graph, m, color, 0) == false)
48+
{
49+
cout<<"Solution does not exist";
50+
return false;
51+
}
52+
53+
printSolution(color);
54+
return true;
55+
}
56+
57+
void printSolution(int color[])
58+
{
59+
cout<<"Solution Exists:"<<" Following are the assigned colors"<<endl;
60+
61+
for (int i = 0; i < V; i++)
62+
cout<<" "<<color[i];
63+
64+
cout<<endl;
65+
}
66+
67+
int main()
68+
{
69+
int graph[V][V];
70+
cout<<"enter adjacency matrix in row major order:"<<endl;
71+
for(int i=0;i<V;i++)
72+
{
73+
for(int j=0;j<V;j++)
74+
{
75+
cin>>graph[i][j];
76+
}
77+
}
78+
79+
int m;
80+
cout<<"enter the number of colors";
81+
cin>>m;
82+
83+
graphColoring (graph, m);
84+
return 0;
85+
}

0 commit comments

Comments
 (0)