-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm-colouring.cpp
68 lines (61 loc) · 1.82 KB
/
m-colouring.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
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//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 isSafe(bool graph[101][101], int cur, int n, int curColor, vector<int> color) {
for (int i = 0; i < n; i++) {
if (graph[cur - 1][i] && color[i + 1] == curColor) return false;
}
return true;
}
bool coloringUtil(bool graph[101][101], int m, int cur, int n, vector<int> &color, int &ans) {
if (cur == n + 1) {
// for (auto ele : color) cout << ele << " ";
// cout << "# " << cur << " " << ans << endl;
for (int i = 1; i <= n; i++) if (color[i] == -1) return false;
if (ans <= m) return true;
return false;
}
for (int i = 1; i <= m; i++) {
if (isSafe(graph, cur, n, i, color)) {
int temp = ans;
ans = max(ans, i);
color[cur] = i;
if (coloringUtil(graph, m, cur + 1, n, color, ans)) return true;
color[cur] = -1;
ans = temp;
}
}
return false;
}
bool graphColoring(bool graph[101][101], int m, int V)
{
vector<int> color(V + 1, -1);
int ans = 0;
return coloringUtil(graph, m, 1, V, color, ans);
}
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, m, e;
cin >> n >> m >> e;
int i;
bool graph[101][101];
for (i = 0; i < n; i++) {
memset(graph[i], 0, sizeof(graph[i]));
}
for (i = 0; i < e; i++) {
int a, b;
cin >> a >> b;
graph[a - 1][b - 1] = 1;
graph[b - 1][a - 1] = 1;
}
cout << graphColoring(graph, m, n) << endl;
}
return 0;
}
// } Driver Code Ends