Graph can be traversed using 

  1. Depth First Traversal or DFS
  2. Breadth First Traversal or BFS

Depth First Traversal

The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It involves exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.

Here, the word backtrack means that when you are moving forward and there are no more nodes along the current path, you move backwards on the same path to find nodes to traverse.  All the nodes will be visited on the current path till all the unvisited nodes have been traversed after which the next path will be selected. This recursive nature of DFS can be implemented using stacks. The basic idea is as follows:

  1. Pick a starting node and push all its adjacent nodes into a stack.
  2. Pop a node from stack to select the next node to visit and push all its adjacent nodes into a stack.
  3. Repeat this process until the stack is empty. However, ensure that the nodes that are visited are marked. This will prevent you from visiting the same node more than once. If you do not mark the nodes that are visited and you visit the same node more than once, you may end up in an infinite loop.

Breadth First Traversal

BFS is a traversing algorithm where you should start traversing from a selected node (source or starting node) and traverse the graph layerwise thus exploring the neighbour nodes (nodes which are directly connected to source node). You must then move towards the next-level neighbour nodes.

As the name BFS suggests, you are required to traverse the graph breadthwise as follows:

  1. First move horizontally and visit all the nodes of the current layer
  2. Move to the next layer

A graph can contain cycles, which may bring you to the same node again while traversing the graph. To avoid processing of same node again, use a boolean array which marks the node after it is processed. While visiting the nodes in the layer of a graph, store them in a manner such that you can traverse the corresponding child nodes in a similar order.

BFS calculates the shortest paths in unweighted graphs. On the other hand, Dijkstra’s algorithm calculates the same thing in weighted graphs. So If all costs are equal, Dijkstra = BFS.

Check step by step implementation at DFS for undirected graphs