Skip to content

Instantly share code, notes, and snippets.

@Dammmien
Last active February 22, 2022 11:37
Show Gist options
  • Save Dammmien/e97391380c3707e30476 to your computer and use it in GitHub Desktop.
Save Dammmien/e97391380c3707e30476 to your computer and use it in GitHub Desktop.
Depth First Search (DFS) Graph Traversal in Javascript
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 );
@iboss-ptk
Copy link

Actually, DFS means that you use a stack which is LIFO not FIFO.

Look at the pseudocode part https://en.wikipedia.org/wiki/Depth-first_search

@thespacecadette
Copy link

DFS uses stacks, stacks are LIFO (push, pop).

Breadth first uses queues, queues are FIFO (shift, unshift or enqueue and dequeue).

@ankitarora05
Copy link

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.

@HRussellZFAC023
Copy link

great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment