Last active
August 29, 2015 14:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="text"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment