-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBipartite.cpp
More file actions
95 lines (82 loc) · 1.42 KB
/
Copy pathBipartite.cpp
File metadata and controls
95 lines (82 loc) · 1.42 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
94
95
#include <iostream>
#include <vector>
#include <queue>
// QUESTION: https://www.techiedelight.com/bipartite-graph/
struct Edge
{
int src;
int dest;
};
class UndirctedGraph {
private:
std::vector<std::vector<int>> adj;
std::vector<bool> visited;
std::vector<int> level;
int nodes;
public:
UndirctedGraph(int n, const std::vector<Edge>& edges)
: nodes(n)
{
adj.resize(nodes);
visited.resize(nodes);
level = std::vector<int>(nodes, -1);
for (const auto& iter : edges)
{
adj[iter.src].push_back(iter.dest);
}
}
void isBipartite()
{
doBFS();
}
private:
void doBFS()
{
bool isbipartite = true;
for (int i = 0; i < nodes; ++i)
{
if (!visited[i])
{
if (!doBFSHelper(i))
{
isbipartite = false;
break;
}
}
}
if (isbipartite)
{
std::cout << "Graph is bipartite" << std::endl;
} else {
std::cout << "Graph is not bipartite" << std::endl;
}
}
bool doBFSHelper(int start)
{
std::queue<int> queue;
queue.push(start);
level[start] = 0;
visited[start] = true;
for (int j : adj[start])
{
if (!visited[j])
{
visited[j] = true;
level[j] = level[start] + 1;
queue.push(j);
} else {
if (level[j] == level[start])
return false;
}
}
return true;
}
};
int main()
{
std::vector<Edge> edges{ {1,2}, {2, 3}, {2, 8}, {3, 4}, {4, 6}, {5, 7}, {5, 9}, {8, 9} };
int n = 10;
UndirctedGraph obj(n, edges);
obj.isBipartite();
return 0;
}