Skip to content

Commit 526fd2e

Browse files
authored
A greedy algorithm for graph coloring
1 parent c1445d2 commit 526fd2e

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/* **** A Greedy algorithm that never uses more than D+1 colors to color all the vertices of a graph, where D is the maximum degree in the graph *** */
2+
/* **** Complexity = O(V^2 + E) where V is number of vertices and E is number of edges *** */
3+
/* **** This is written in C++14 *** */
4+
5+
#include <iostream>
6+
#include <vector>
7+
#include <map>
8+
#include <set>
9+
using namespace std;
10+
11+
struct Edge {
12+
int sourceVertex, destinationVertex;
13+
};
14+
15+
//You can add Other Colors too
16+
string color[] =
17+
{
18+
"", "BLUE", "GREEN", "RED", "YELLOW", "ORANGE", "PINK",
19+
"BLACK", "BROWN", "WHITE", "PURPLE", "VOILET"
20+
};
21+
22+
class Graph
23+
{
24+
public:
25+
vector<int> *adjacencyList;
26+
Graph(vector<Edge> const &edges, int N)
27+
{
28+
adjacencyList = new vector<int>[N];
29+
for (int i = 0; i < edges.size(); i++)
30+
{
31+
int src = edges[i].sourceVertex;
32+
int dest = edges[i].destinationVertex;
33+
adjacencyList[src].push_back(dest);
34+
adjacencyList[dest].push_back(src);
35+
}
36+
}
37+
~Graph() {
38+
delete[] adjacencyList;
39+
}
40+
};
41+
42+
void colorGraph(const Graph &graph, int N)
43+
{
44+
map<int, int> result;
45+
for (int u = 0; u < N; u++)
46+
{
47+
set<int> assigned;
48+
for (int i : graph.adjacencyList[u]) {
49+
if (result[i]) {
50+
assigned.insert(result[i]);
51+
}
52+
}
53+
int color = 1;
54+
for (auto &c: assigned ) {
55+
if (color != c) {
56+
break;
57+
}
58+
color++;
59+
}
60+
result[u] = color;
61+
}
62+
for (int v = 0; v < N; v++) {
63+
cout << "Color assigned to vertex " << v << " is "
64+
<< color[result[v]] << '\n';
65+
}
66+
}
67+
68+
int main()
69+
{
70+
int N;
71+
cout<<"\nEnter number of vertices in the graph : ";
72+
cin>>N;
73+
74+
int E;
75+
cout<<"\nEnter number of edges in the graph : ";
76+
cin>>E;
77+
78+
int temp1, temp2;
79+
cout << "\nEnter edges in pair ,where each pair is represented by starting vertex and ending vertex.";
80+
cout<<"\nVertex number starts from 0 till "<<N-1;
81+
cout << "\nFor Example, edge between vertex 4 and vertex 5 is given like \n4 5\n";
82+
83+
vector<Edge> edges;
84+
int counter=E;
85+
while(E--)
86+
{
87+
temp1=-1;
88+
temp2=-1;
89+
90+
while(temp1<0 || temp2<0 || temp1>=N || temp2>=N)
91+
{
92+
cout << "\nEnter Edge "<< counter - E -1<<" According to above format\n";
93+
cin>>temp1;
94+
cin>>temp2;
95+
}
96+
edges.push_back({temp1,temp2});
97+
98+
}
99+
/*
100+
edges =
101+
{
102+
{0, 1}, {0, 4}, {0, 5}, {4, 5}, {1, 4}, {1, 3}, {2, 3}, {2, 4}
103+
};
104+
*/
105+
Graph graph(edges, N);
106+
colorGraph(graph, N);
107+
return 0;
108+
}

0 commit comments

Comments
 (0)