AfterAcademy Tech
•
10 Feb 2020

For graph traversal, we normally use Breadth-First Search or Depth-First Search. In the last blog, we learned about Breadth-First Search. Now, in this blog, we will be learning about the other graph traversal algorithm i.e. Depth-First Search or DFS. So, let's get started.
Depth-First Search or simply DFS is a graph traversal algorithm that uses the concept of backtracking or exhaustive search.
In DFS, we keep on visiting the nodes until there is some neighbour node and if there is no neighbour node then we backtrack to the previous node and again we will visit all the nodes ahead of that node. This can also be performed with the help of the exhaustive search.
All you need to do is just select one path and traverse to the end of this path and after that, come back to the previous node and traverse the nodes that are connected to those nodes and this process is going to continue again and again until there is some node that is not traversed.
If we reach the end of one path, then we come back to the recently visited node. So, while writing the code for the DFS algorithm, we are going to use the Stack data structure because Stack uses the Last In First Out order i.e. LIFO order.
The following steps will be followed to implement the DFS:
Now, let's look at the pseudocode of the above implementation:
DFS (G, s): //here, G is the Graph and s is the source/starting node
let S be the stack
S.push( s ) //pushing source node in stack S
mark s as visited.
while ( S is not empty):
//Pop a node from the stack S
v = S.top( )
S.pop( )
//Push all the neighbours of v in stack that are not visited
for all neighbours w of v in Graph G:
if w is not visited :
S.push( w )
mark w as visited
Let's understand the above pseudocode with the help of one example:



These are some of the applications of Depth-First Search.
Happy Learning, Enjoy Algorithms!
Team AfterAcademy!
AfterAcademy Tech
In this blog, we will learn Breadth First Search that is used for Graph Traversal i.e. the Breadth First Search is used to traverse each and every node of a graph. So, let's learn together.

AfterAcademy Tech
Given a sorted integer array arr[] of n elements and a target value k, write a program to search k in arr[]. The famous binary search algorithm is easy to implement and the best optimization technique for performing searching operations

AfterAcademy Tech
You are given a matrix arr of m x n size. Write a program to searches for a value k in arr. This arr has the following properties: - Integers in each row are sorted from left to right. - The first value of each row is greater than the last value of previous row. This is a basic optimization problem that will clear the concept of searching.

AfterAcademy Tech
It is important to know traversal techniques in a tree before solving tree problems. We have discussed the 3 primary traversals in a tree at length in this blog with both recursive and iterative implementations.
