-
-
Save easyrider/d87e86e0e91e5d3a55ab1e50a8596bbf to your computer and use it in GitHub Desktop.
Breadth First Search (BFS) Graph Traversal in Javascript
This file contains hidden or 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
var nodes = [ | |
{ | |
links: [ 1 ], // node 0 is linked to node 1 | |
visited: false | |
}, { | |
links: [ 0, 2 ], // node 1 is linked to node 0 and 2 | |
path: [], | |
visited: false | |
}, | |
... | |
]; | |
function bfs( start ) { | |
var listToExplore = [ start ]; | |
nodes[ start ].visited = true; | |
while ( listToExplore.length > 0 ) { | |
var nodeIndex = listToExplore.shift(); | |
nodes[ nodeIndex ].links.forEach( function( childIndex ) { | |
if ( !nodes[ childIndex ].visited ) { | |
nodes[ childIndex ].visited = true; | |
listToExplore.push( childIndex ); | |
} | |
} ); | |
} | |
}; | |
bfs( 0 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment