forked from Thelalitagarwal/GFG_Daily_Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathM-Coloring Problem.cpp
More file actions
40 lines (36 loc) · 1.11 KB
/
M-Coloring Problem.cpp
File metadata and controls
40 lines (36 loc) · 1.11 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
class Solution{
public:
// Function to determine if graph can be coloured with at most M colours such
// that no two adjacent vertices of graph are coloured with same colour.
bool isValid(int index, int col, bool graph[101][101], int n, vector<int> &colour)
{
for(int i = 0;i<=n;i++)
{
if(graph[index][i]==1)
{
if(col == colour[i])
return 0;
}
}
return 1;
}
bool solve(bool graph[101][101], int n, int m, int index, vector<int> &colour)
{
if(index>=n) return 1;
for(int col = 1;col<=m;col++)
{
if(isValid(index, col, graph, n, colour))
{
colour[index]=col;
if(solve(graph, n, m, index+1, colour)==1)
return 1;
else colour[index]=0;
}
}
return 0;
}
bool graphColoring(bool graph[101][101], int m, int n) {
vector<int> colour(n, 0);
return solve(graph, n, m, 0, colour);
}
};