-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcheck_bipartite_dfs.cpp
48 lines (40 loc) · 991 Bytes
/
check_bipartite_dfs.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
#include <bits/stdc++.h>
using namespace std;
/*
https://youtu.be/-vu34sct1g8
Visited matrix: have color matrix
dfs(1, 0) = color node 1 with color 0
and call dfs(2, !0)
*/
class Solution
{
private:
bool dfs(int node, int curr_color, vector<vector<int>> graph, vector<int> &color)
{
color[node] = curr_color;
for (auto it : graph[node])
{
if (color[it] == -1)
{
if(dfs(it, !curr_color, graph, color) == false)
return false;
}
else if (color[it] == curr_color)
return false;
}
return true;
}
public:
bool isBipartite(vector<vector<int>> &graph)
{
int V = graph.size();
vector<int> color(V, -1);
for (int i = 0; i < V; i++)
if (color[i] == -1)
{
if (dfs(i, 0, graph, color) == false)
return false;
}
return true;
}
};