Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active August 29, 2015 14:00
Show Gist options
  • Save kavitshah8/11220118 to your computer and use it in GitHub Desktop.
Save kavitshah8/11220118 to your computer and use it in GitHub Desktop.
Adds a color attribute to the objects to implement breadth first search algorithm.
/* A ---- B ----- C
| |
| |
D ------ E ------ F */
var allNodes = {
A : { "color": "WHITE" , "value": 20, "neighbours": ["D","B"] },
B : { "color": "WHITE" , "value": 10, "neighbours": ["A","E","C"] },
C : { "color": "WHITE" , "value": 30, "neighbours": ["B"] },
D : { "color": "WHITE" , "value": 20, "neighbours": ["A","E"] },
E : { "color": "WHITE" , "value": 90, "neighbours": ["D","B","F"] },
F : { "color": "WHITE" , "value": 90, "neighbours": ["E"] }
};
function getMaxValue(root){
var visited_nodes;
var max = 0;
if( allNodes[root]["value"] > max ){
max = allNodes[root]["value"];
}
// Implements breadth first search algorithm to traverse the graph
// For given problem, running time is big-O(# edges in the graph )
allNodes[root]["color"] = "GRAY";
visited_nodes = [];
visited_nodes.push( allNodes[root] );
while( visited_nodes.length != 0 ){
var u = visited_nodes.pop( );
for(i = 0; i < u["neighbours"].length; i++){
var v = allNodes[ u["neighbours"][i] ];
if( v["color"]==="WHITE"){
v["color"] = "GRAY";
visited_nodes.push( v );
if( v["value"] > max ){
max = v["value"];
}
}
}
u["color"]="BLACK";
}
reset(allNodes);
return max;
}
function reset(nodes){
for (var key in nodes) {
nodes[key].color = "WHITE";
};
};
var r = getMaxValue('A');
document.getElementById('text').innerHTML = "Maximum is : " + r;
<div id="text"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment