Skip to content

Instantly share code, notes, and snippets.

@NamPE286
Last active April 4, 2023 18:03
Show Gist options
  • Save NamPE286/38e1071fae6201ba3d31c595001bc9cf to your computer and use it in GitHub Desktop.
Save NamPE286/38e1071fae6201ba3d31c595001bc9cf to your computer and use it in GitHub Desktop.
Check if a graph is bipartite using DFS bicoloring
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool is_bipartite(unordered_map<ll, vector<ll>> &graph, vector<ll> &color, ll curNode = 1, ll curColor = 1) {
if(color[curNode]) return true;
color[curNode] = curColor;
bool ans = true;
for(ll i : graph[curNode]){
if(color[curNode] == color[i]) return false;
ans = min(ans, is_bipartite(graph, color, i, -curColor));
}
return ans;
}
int main() {
ll nodeNum, edgeNum;
cin >> nodeNum >> edgeNum;
unordered_map<ll, vector<ll>> graph;
for (ll i = 0; i < edgeNum; i++) {
ll a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
vector<ll> color(nodeNum + 1);
cout << is_bipartite(graph, color);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment