Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code to check if graph is bipartite #25

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions bipartite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const GraphBase = require('./graph-base');
const Queue = require('./ds/queue');
const BFS = require('./bfs');

class Bipartite extends BFS{
constructor(numVertices = 0, numEdges = 0, startingPoint = 0) {
super(numVertices,numEdges);
this.startingPoint = startingPoint;
}
isBipartite(){

let bfs_order = this.bfs();
let Adj = this.getSimpleAdj();

let ans = true;
if(bfs_order.length != this.numVertices){ //Cyclicity Check
ans = false;
}

let color = [];
Adj.forEach((value, key) => {
color[key] = 0;
});

color[bfs_order[0]] = 1;
for (let i = 0; i < bfs_order.length; i++) {
let node = bfs_order[i];

for (let j = 0; j < Adj.get(node).length; j++) {

if (!color[Adj.get(node)[j]]) {
color[Adj.get(node)[j]] = -1*color[bfs_order[i]];
}
else if(color[Adj.get(node)[j]] == color[bfs_order[i]]){
ans = false;
}

}
}
return ans;
}
}

// const g = new Bipartite(4)
// vertices = [0,1,2,3]
// for(let i=0;i<vertices.length;i++)
// {
// g.addVertex(vertices[i])
// }
// g.addEdge(0,1);
// g.addEdge(0, 2);
// g.addEdge(1,2);
// g.addEdge(2,0);
// g.addEdge(2,3);
// g.addEdge(3,3);

// console.log(g.getSimpleAdj())
// console.log(g.isBipartite())

module.exports = Bipartite;