Skip to content

Commit 0925eb6

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

File tree

3 files changed

+57
-1
lines changed

3 files changed

+57
-1
lines changed

algorithm/graph_search/bfs/desc.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
],
1919
"files": {
2020
"tree": "Searching a tree",
21-
"shortest_path": "Finding the shortest path"
21+
"shortest_path": "Finding the shortest path",
22+
"test_bipartiteness": "Test if graph is biparted (or 2-colorable)"
2223
}
2324
}
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
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
var tracer = new UndirectedGraphTracer();
2+
var logger = new LogTracer();
3+
tracer.attach(logger);
4+
5+
var G =[
6+
[0, 1, 0, 1, 1],
7+
[1, 0, 1, 0, 0],
8+
[0, 1, 0, 1, 0],
9+
[1, 0, 1, 0, 0], // <-- replace latest 0 with 1 to make G not biparted
10+
[1, 0, 0, 0, 0],
11+
];
12+
tracer._setData(G, 0);
13+
14+
var colorsTracer = new Array1DTracer('Colors');

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy