Graphs 101: Let’s BFS and DFS.
In this article we will dive into graph basics.
The 2 most common used representation of graphs are the adjacency list and adjacency matrix.
Adjacency list
Graph Traversals
There are two graph traversals: breadth first search and depth first search.
Breadth First Search
BFS visits the nodes one level at a time. To prevent visiting the same node more than once, we’ll maintain a visited object.
For BFS we utilize a Queue to process the nodes in a First In First Out fashion. The time complexity is O(v+e).
Pseudocode
Code
Depth First Search
DFS visits the nodes depth wise so we will use a Stack in order to process Last In First Out fashion.
Starting from a vertex, we’ll push the neighboring vertices to our stack. Whenever a vertex is popped, it is marked visited in our visited object. Its neighboring vertices are pushed to the stack. Since we are always popping a new adjacent vertex, our algorithm will always explore a new level.
We can also use the intrinsic stack calls to implement DFS recursively.
The time complexity is the same as BFS, O(v+e).
Pseudocode
Code
There it is, now let’s see how to use this to solve problems.