TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
is_graph_bipartite.cpp
Go to the documentation of this file.
1
34#include <iostream>
35#include <queue>
36#include <vector>
37
42namespace graph {
47namespace is_graph_bipartite {
51class Graph {
52 private:
53 int n;
54
55 std::vector<std::vector<int> >
57
58 std::vector<int> side;
59
60 public:
65 explicit Graph(int size) {
66 n = size;
67 adj.resize(n);
68 side.resize(n, -1);
69 }
70
71 void addEdge(int u, int v);
72
73 bool
74 is_bipartite();
75};
76
83void Graph::addEdge(int u, int v) {
84 adj[u - 1].push_back(v - 1);
85 adj[v - 1].push_back(u - 1);
86}
87
107 bool check = true;
108 std::queue<int> q;
109 for (int current_edge = 0; current_edge < n; ++current_edge) {
110 if (side[current_edge] == -1) {
111 q.push(current_edge);
112 side[current_edge] = 0;
113 while (q.size()) {
114 int current = q.front();
115 q.pop();
116 for (auto neighbour : adj[current]) {
117 if (side[neighbour] == -1) {
118 side[neighbour] = (1 ^ side[current]);
119 q.push(neighbour);
120 } else {
121 check &= (side[neighbour] != side[current]);
122 }
123 }
124 }
125 }
126 }
127 return check;
128}
129} // namespace is_graph_bipartite
130} // namespace graph
131
136static void test() {
138 5);
140 G1.addEdge(1, 2);
141 G1.addEdge(1, 3);
142 G1.addEdge(3, 4);
143 G1.addEdge(4, 5);
144
146 3);
148 G2.addEdge(1, 2);
149 G2.addEdge(1, 3);
150 G2.addEdge(2, 3);
151
153 if (G1.is_bipartite()) {
154 std::cout << "The given graph G1 is a bipartite graph\n";
155 } else {
156 std::cout << "The given graph G1 is not a bipartite graph\n";
157 }
158 if (G2.is_bipartite()) {
159 std::cout << "The given graph G2 is a bipartite graph\n";
160 } else {
161 std::cout << "The given graph G2 is not a bipartite graph\n";
162 }
163}
164
168int main() {
169 test();
170 return 0;
171}
Class for representing graph as an adjacency list.
Graph(int size)
Constructor that initializes the graph on creation.
void addEdge(int u, int v)
Function that add an edge between two nodes or vertices of graph.
std::vector< int > side
stores the side of the vertex
std::vector< std::vector< int > > adj
adj stores the graph as an adjacency list
bool is_bipartite()
function to add edges to our graph
static void test()
int main()
Graph Algorithms.
Functions for checking whether a graph is bipartite or not.