Skip to content

Instantly share code, notes, and snippets.

@siddhantkushwaha
Created October 17, 2019 18:30
Show Gist options
  • Save siddhantkushwaha/e23c102b1a6138d10e9c0fad1302a2d7 to your computer and use it in GitHub Desktop.
Save siddhantkushwaha/e23c102b1a6138d10e9c0fad1302a2d7 to your computer and use it in GitHub Desktop.
Graph implementations
typedef vector<vector<int>> graph;
graph create(int n, vector<vector<int>> &edges) {
graph adj(n, vector<int>(0));
for(auto e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
return adj;
}
bool check_bipartite(graph &adj, vector<int> &vis, int idx) {
queue<int> q;
vis[idx] = 0;
q.push(idx);
while(!q.empty()) {
int v = q.front();
q.pop();
for(int x: adj[v]) {
/* give alternate color and push in queue */
if(vis[x] == -1) {
vis[x] = 1 - vis[v];
q.push(x);
}
/* not bipartite if same color */
if(vis[v] == vis[x])
return false;
}
}
return true;
}
int find_unvisited(vector<int> &vis) {
int idx = -1;
for(int i=0; i<vis.size(); i++)
if(vis[i] == -1) {
idx = i;
break;
}
return idx;
}
int solve(int A, vector<vector<int> > &B) {
auto adj = create(A, B);
/* -1, 0(red), 1(black) */
vector<int> vis(adj.size(), -1);
// keep checking till nodes are colored
bool ans = true;
int idx = find_unvisited(vis);
while(idx > -1) {
ans = ans && check_bipartite(adj, vis, idx);
if(ans == false)
return 0;
idx = find_unvisited(vis);
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment