Skip to content

Instantly share code, notes, and snippets.

@vagusX
Forked from Dammmien/dfs.js
Created March 31, 2017 04:05
Show Gist options
  • Save vagusX/cbfd193ae4804a675cb72109c74fa507 to your computer and use it in GitHub Desktop.
Save vagusX/cbfd193ae4804a675cb72109c74fa507 to your computer and use it in GitHub Desktop.
Depth First Search (DFS) 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
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