diff --git a/algorithm/graph_search/bfs/desc.json b/algorithm/graph_search/bfs/desc.json index 743e0c98..0e39e3cb 100644 --- a/algorithm/graph_search/bfs/desc.json +++ b/algorithm/graph_search/bfs/desc.json @@ -18,6 +18,7 @@ ], "files": { "tree": "Searching a tree", - "shortest_path": "Finding the shortest path" + "shortest_path": "Finding the shortest path", + "test_bipartiteness": "Test if graph is biparted (or 2-colorable)" } } diff --git a/algorithm/graph_search/bfs/test_bipartiteness/code.js b/algorithm/graph_search/bfs/test_bipartiteness/code.js new file mode 100644 index 00000000..da6484e8 --- /dev/null +++ b/algorithm/graph_search/bfs/test_bipartiteness/code.js @@ -0,0 +1,41 @@ +function BFSCheckBipartiteness(s) { + var Q = []; + + // Create a new matrix to set colors (0,1) + var Colors = []; + for (var _i = 0; _i < G.length; _i++) Colors[_i] = -1; + colorsTracer._setData(Colors); + + Colors[s] = 1; + colorsTracer._notify(s, 1); + + Q.push(s); // add start node to queue + + while (Q.length > 0) { + var node = Q.shift(); // dequeue + tracer._visit(node)._wait(); + + for (var i = 0; i < G[node].length; i++) { + if (G[node][i]) { + + if (Colors[i] === -1) { + + Colors[i] = 1 - Colors[node]; + colorsTracer._notify(i, 1 - Colors[node]); + + Q.push(i); + tracer._visit(i, node)._wait(); + + } else if (Colors[i] == Colors[node]) { + logger._print('Graph is not biparted'); + return false; + } + } + } + } + + logger._print('Graph is biparted'); + return true; +} + +BFSCheckBipartiteness(0); \ No newline at end of file diff --git a/algorithm/graph_search/bfs/test_bipartiteness/data.js b/algorithm/graph_search/bfs/test_bipartiteness/data.js new file mode 100644 index 00000000..36835cd7 --- /dev/null +++ b/algorithm/graph_search/bfs/test_bipartiteness/data.js @@ -0,0 +1,14 @@ +var tracer = new UndirectedGraphTracer(); +var logger = new LogTracer(); +tracer.attach(logger); + +var G =[ +[0, 1, 0, 1, 1], +[1, 0, 1, 0, 0], +[0, 1, 0, 1, 0], +[1, 0, 1, 0, 0], // <-- replace latest 0 with 1 to make G not biparted +[1, 0, 0, 0, 0], +]; +tracer._setData(G, 0); + +var colorsTracer = new Array1DTracer('Colors'); \ No newline at end of file
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: