forked from Ayushsinhahaha/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacktrack.cpp
104 lines (87 loc) · 1.98 KB
/
backtrack.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Number of vertices in the graph
#define V 4
void printSolution(int color[]);
// check if the colored
// graph is safe or not
bool isSafe(bool graph[V][V], int color[])
{
// check for every edge
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;
}
/* This function solves the m Coloring
problem using recursion. It returns
false if the m colours cannot be assigned,
otherwise, return true and prints
assignments of colours to all vertices.
Please note that there may be more than
one solutions, this function prints one
of the feasible solutions.*/
bool graphColoring(bool graph[V][V], int m, int i,
int color[V])
{
// if current index reached end
if (i == V) {
// if coloring is safe
if (isSafe(graph, color)) {
// Print the solution
printSolution(color);
return true;
}
return false;
}
// Assign each color from 1 to m
for (int j = 1; j <= m; j++) {
color[i] = j;
// Recur of the rest vertices
if (graphColoring(graph, m, i + 1, color))
return true;
color[i] = 0;
}
return false;
}
/* A utility function to print solution */
void printSolution(int color[])
{
cout << "Solution Exists:"
" Following are the assigned colors \n";
for (int i = 0; i < V; i++)
cout << " " << color[i];
cout << "\n";
}
// Driver code
int main()
{
/* Create following graph and
test whether it is 3 colorable
(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
// 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;
// Function call
if (!graphColoring(graph, m, 0, color))
cout << "Solution does not exist";
return 0;
}
// This code is contributed by shivanisinghss2110