forked from Harshita-Kanal/Data-Structures-and-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmColoring.cpp
More file actions
93 lines (72 loc) · 1.3 KB
/
mColoring.cpp
File metadata and controls
93 lines (72 loc) · 1.3 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
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
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
class node
{
public:
int color = 1;
set<int> edges;
};
int canPaint(vector<node>& nodes, int n, int m)
{
vector<int> visited(n + 1, 0);
int maxColors = 1;
for (int sv = 1; sv <= n; sv++)
{
if (visited[sv])
continue;
visited[sv] = 1;
queue<int> q;
q.push(sv);
while (!q.empty())
{
int top = q.front();
q.pop();
for (auto it = nodes[top].edges.begin();
it != nodes[top].edges.end(); it++)
{
if (nodes[top].color == nodes[*it].color)
nodes[*it].color += 1;
maxColors
= max(maxColors, max(nodes[top].color,
nodes[*it].color));
if (maxColors > m)
return 0;
if (!visited[*it]) {
visited[*it] = 1;
q.push(*it);
}
}
}
}
return 1;
}
// Driver code
int main()
{
int n = 4;
bool graph[n][n] = {
{ 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 1 },
{ 1, 0, 1, 0 }};
int m = 3; // Number of colors
vector<node> nodes(n + 1);
// Add edges to each node as per given input
for (int i = 0; i < n; i++)
{
for(int j =0;j<n;j++)
{
if(graph[i][j])
{
// Connect the undirected graph
nodes[i].edges.insert(i);
nodes[j].edges.insert(j);
}
}
}
// Display final answer
cout << canPaint(nodes, n, m);
cout << "\n";
return 0;
}