-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path785 - Is Graph Bipartite.cpp
61 lines (52 loc) · 1.28 KB
/
785 - Is Graph Bipartite.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
#include <bits/stdc++.h>
using namespace std;
// BFS method of finding bipartite but coloring leads to a better looking code
// WHAT BRUH?? this is way worse than dfs lol EDIT: 15-10-21
class Solution
{
public:
bool isBipartiteUtil(vector<vector<int>> &graph, vector<bool> &visited, vector<int> &color, int root)
{
bool result = true;
queue<int> q;
q.push(root);
visited[root] = true;
int offset = 0;
while (!q.empty())
{
int size = q.size();
for (int i = 0; i < size; i++)
{
int curr = q.front();
visited[curr] = true;
if (color[curr] == (offset + 1) % 2)
return false;
else
color[curr] = offset % 2;
for (int neighbour : graph[curr])
{
if (visited[neighbour] == false)
q.push(neighbour);
}
q.pop();
}
offset++;
}
return result;
}
bool isBipartite(vector<vector<int>> &graph)
{
int n = graph.size(), m = graph[0].size();
bool result = false;
vector<bool> visited(n, false);
vector<int> color(n, -1);
for (int i = 0; i < n; i++)
{
if (visited[i] == false)
result = isBipartiteUtil(graph, visited, color, i);
if (result == false)
break;
}
return result;
}
};