Last active
February 22, 2022 11:37
-
-
Save Dammmien/e97391380c3707e30476 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
const 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 | |
}, | |
... | |
]; | |
const dfs = start => { | |
const listToExplore = [ start ]; | |
nodes[ start ].visited = true; | |
while ( listToExplore.length ) { | |
const nodeIndex = listToExplore.pop(); | |
nodes[ nodeIndex ].links.forEach( childIndex => { | |
if ( !nodes[ childIndex ].visited ) listToExplore.push( childIndex ); | |
nodes[ childIndex ].visited = true; | |
} ); | |
} | |
}; | |
dfs( 0 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great!