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 ); |
DFS ---> Stack ---> By storing the vertices in a stack, the vertices are explored by lurching along a path, visiting a new adjacent vertex if there is one available.
BFS ----> Queue ----> By storing the vertices in a queue, the oldest unexplored vertices are explored first.
great!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DFS uses stacks, stacks are LIFO (push, pop).
Breadth first uses queues, queues are FIFO (shift, unshift or enqueue and dequeue).