TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
is_graph_bipartite2.cpp
1
17#include <cassert>
18#include <cstdint>
19#include <iostream>
20#include <queue>
21#include <vector>
22
27namespace graph {
37bool checkBipartite(const std::vector<std::vector<int64_t>> &graph,
38 int64_t index, std::vector<int64_t> *visited) {
39 std::queue<int64_t> q;
41 q.push(index);
42 (*visited)[index] = 1;
43 while (q.size()) {
44 int64_t u = q.front();
45 q.pop();
46 for (uint64_t i = 0; i < graph[u].size(); i++) {
47 int64_t v =
48 graph[u][i];
49 if (!(*visited)[v])
51 {
52 (*visited)[v] =
53 ((*visited)[u] == 1)
54 ? -1
55 : 1;
57 q.push(v);
58 } else if ((*visited)[v] ==
59 (*visited)[u])
62 {
63 return false;
64 }
65 }
66 }
67 return true;
69}
76bool isBipartite(const std::vector<std::vector<int64_t>> &graph) {
77 std::vector<int64_t> visited(
78 graph.size());
81
82 for (uint64_t i = 0; i < graph.size(); i++) {
83 if (!visited[i])
86 {
87 if (!checkBipartite(graph, i, &visited)) {
88 return false;
89 }
90 }
91 }
92 return true;
93}
94} // namespace graph
95
100static void test() {
101 std::vector<std::vector<int64_t>> graph = {{1, 3}, {0, 2}, {1, 3}, {0, 2}};
102
103 assert(graph::isBipartite(graph) ==
104 true);
106
107 std::vector<std::vector<int64_t>> graph_not_bipartite = {
108 {1, 2, 3}, {0, 2}, {0, 1, 3}, {0, 2}};
109
110 assert(graph::isBipartite(graph_not_bipartite) ==
111 false);
113 std::cout << "All tests have successfully passed!\n";
114}
123int main() {
124 test(); // run self-test implementations
125 return 0;
126}
void test()
int main()
Main function.
Graph Algorithms.
bool isBipartite(const std::vector< std::vector< int64_t > > &graph)
returns true if the given graph is bipartite else returns false
bool checkBipartite(const std::vector< std::vector< int64_t > > &graph, int64_t index, std::vector< int64_t > *visited)
function to check whether the passed graph is bipartite or not