forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_coloring.cpp
83 lines (64 loc) · 1.61 KB
/
graph_coloring.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<bits/stdc++.h>
using namespace std;
#define V 4
void printSolution(int color[]){
for(int i = 0; i < V; i++)
cout<<color[i]<<" ";
}
bool isSafe(int v, bool graph[V][V],int color[], int c){
// If adjacent vertices are of same color return false
for (int i = 0; i < V; i++)
if(graph[v][i] && c == color[i])
return false;
return true;
}
bool graphColoringUtil(bool graph[V][V], int m, int color[], int v){
// If all vertices are assigned a color then return true */
if(v == V)
return true;
// Consider this vertex v and try out different colors
for(int c = 1; c <= m; c++) {
// Check if assignment of color c to v is fine
if(isSafe(v, graph, color, c)){
color[v] = c;
// recur to assign colors to rest of the vertices
if (graphColoringUtil(graph, m, color, v + 1) == true)
return true;
// If assigning color c doesn't lead to a solution then remove it
color[v] = 0;
}
}
// If no color can be assigned to this vertex
return false;
}
bool graphColoring(bool graph[V][V], int m){
// Initialize all color values as 0.
// This initialization is needed correct functioning of isSafe()
int color[V];
for(int i = 0; i < V; i++)
color[i] = 0;
if (graphColoringUtil(graph, m, color, 0) == false) { // <graph, m, color, vertex>
cout<<"Solution does not exist";
return false;
}
else printSolution(color);
return true;
}
int main(){
/* Given graph
(3)---(2)
| / |
| / |
| / |
(0)---(1)
*/
bool graph[V][V] = {
{ 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 1 },
{ 1, 0, 1, 0 },
};
int m = 3; // Number of colors
graphColoring(graph, m);
return 0;
}