Skip to content

Instantly share code, notes, and snippets.

@Dammmien
Last active February 22, 2022 11:35
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Dammmien/9d264fc0ceba1f843c80 to your computer and use it in GitHub Desktop.
Save Dammmien/9d264fc0ceba1f843c80 to your computer and use it in GitHub Desktop.
Breadth First Search (BFS) Graph Traversal in Javascript
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