vector<vi> g;
int V;
bool isBipartiteUtil(int s, vi &color) {
queue<int> q;
q.push(s);
color[s] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto v : g[u]) {
// if self-edges are possible, and not allowed
if (u == v)
return false;
// if have not assigned a color, assign and push onto queue
if (color[v] == -1)
color[v] = 1 - color[u], q.push(v);
// if color is assigned, and it matches the color of our adjacent parent,
// not bipartite
else if (color[v] == color[u])
return false;
}
}
return true;
}
// Works for graphs that may not be strongly connected
bool isBipartite() {
vi color(V, -1);
for (int i = 0; i < V; i++) {
if (color[i] == -1) {
if (!isBipartiteUtil(i, color))
return false;
}
}
return true;
}