Added BFS bipartiteness algorithm · odingit/AlgorithmVisualizer@0925eb6 · GitHub
Skip to content

Commit 0925eb6

Browse files
committed
Added BFS bipartiteness algorithm
AKA: Graph is 2-colorable.
1 parent 6b5f1a8 commit 0925eb6

3 files changed

Lines changed: 57 additions & 1 deletion

File tree

algorithm/graph_search/bfs/desc.json

Lines changed: 2 additions & 1 deletion
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
function BFSCheckBipartiteness(s) {
2+
var Q = [];
3+
4+
// Create a new matrix to set colors (0,1)
5+
var Colors = [];
6+
for (var _i = 0; _i < G.length; _i++) Colors[_i] = -1;
7+
colorsTracer._setData(Colors);
8+
9+
Colors[s] = 1;
10+
colorsTracer._notify(s, 1);
11+
12+
Q.push(s); // add start node to queue
13+
14+
while (Q.length > 0) {
15+
var node = Q.shift(); // dequeue
16+
tracer._visit(node)._wait();
17+
18+
for (var i = 0; i < G[node].length; i++) {
19+
if (G[node][i]) {
20+
21+
if (Colors[i] === -1) {
22+
23+
Colors[i] = 1 - Colors[node];
24+
colorsTracer._notify(i, 1 - Colors[node]);
25+
26+
Q.push(i);
27+
tracer._visit(i, node)._wait();
28+
29+
} else if (Colors[i] == Colors[node]) {
30+
logger._print('Graph is not biparted');
31+
return false;
32+
}
33+
}
34+
}
35+
}
36+
37+
logger._print('Graph is biparted');
38+
return true;
39+
}
40+
41+
BFSCheckBipartiteness(0);
Lines changed: 14 additions & 0 deletions

0 commit comments

Comments
 (0)