Learning Graphs Part 2: Traversal

123jackcole

Jack Cole

Posted on August 23, 2020

Learning Graphs Part 2: Traversal

In my last post we covered how to implement a graph in javascript.

In this week's post we'll be going over how to traverse through a graph. Similar to our traversal of binary search trees, there are two main methods of traversal that we'll be using. Breadth-first search(BFS) and depth-first search(DFS).

However, for our graph searches we're going to need to keep track of which nodes we've traversed to. If we didn't we could potentially visit the same node multiple times due to nodes in a graph potentially having multiple vertices.

Breadth First Search

For our BFS function we're going to start by creating a visited array and populate it with boolean values for each node in our graph.

We'll then use a queue to keep track of nodes we need to visit and fill it with our starting node.

Then we loop through our queue and view our current node and its edges.

From there we loop through the nodes edges. If we have yet to visit the node we add it to the queue and mark it as visited.

BFS

Depth First Search

For our DFS function we're going to utilize a recursive helper function instead of a queue of stack.

We'll start in the same fashion with creating and populating a visited array.

Then we'll pass our node and our visited array into our helper function.

The function will set the node to visited, get its edges, loop through the edges, and pass non visited edges into our recursive function.

DFS

Thanks for reading! The code for my graph posts can be found here.

💖 💪 🙅 🚩
123jackcole
Jack Cole

Posted on August 23, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to Solve a Coding Challenge
beginners How to Solve a Coding Challenge

November 22, 2020

Learning Heaps in Javascript
beginners Learning Heaps in Javascript

September 12, 2020

Learning Tries in Javascript
beginners Learning Tries in Javascript

September 6, 2020

Learning Graphs Part 2: Traversal
beginners Learning Graphs Part 2: Traversal

August 23, 2020