-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_col.cpp
More file actions
59 lines (54 loc) · 1.09 KB
/
graph_col.cpp
File metadata and controls
59 lines (54 loc) · 1.09 KB
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
#include <stdbool.h>
#include <stdio.h>
#define V 4
void printSolution(int color[]);
bool isSafe(bool graph[V][V], int color[])
{
for (int i = 0; i < V; i++)
for (int j = i + 1; j < V; j++)
if (graph[i][j] && color[j] == color[i])
return false;
return true;
}
bool graphColoring(bool graph[V][V], int m, int i,
int color[V])
{
if (i == V) {
if (isSafe(graph, color)) {
printSolution(color);
return true;
}
return false;
}
for (int j = 1; j <= m; j++) {
color[i] = j;
if (graphColoring(graph, m, i + 1, color))
return true;
color[i] = 0;
}
return false;
}
void printSolution(int color[])
{
printf("Solution Exists:"
" Following are the assigned colors \n");
for (int i = 0; i < V; i++)
printf(" %d ", color[i]);
printf("\n");
}
int main()
{
bool graph[V][V] = {
{ 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 1 },
{ 1, 0, 1, 0 },
};
int m = 3;
int color[V];
for (int i = 0; i < V; i++)
color[i] = 0;
if (!graphColoring(graph, m, 0, color))
printf("Solution does not exist");
return 0;
}