-
-
Save vagusX/cbfd193ae4804a675cb72109c74fa507 to your computer and use it in GitHub Desktop.
Depth First Search (DFS) Graph Traversal in Javascript
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
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 | |
visited: false | |
}, | |
... | |
]; | |
function dfs( 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 ); | |
} | |
} ); | |
} | |
}; | |
dfs( 0 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment