Searching a Graph in Data Structure


We know that the graph is one non-linear data structure. In this data structure, we put some values into nodes, and the nodes are connected though different edges. As we can store data into the graph structure, we also need to search elements from the graph to use them.

For searching in graphs, there are two different methods. The Breadth First Search and the Depth First searching techniques.

Breadth First Search (BFS)

The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertex and checks its adjacent vertices again. To implement this algorithm, we need to use the Queue data structure. All the adjacent vertices are added into the queue when all adjacent vertices are completed, one item is removed from the queue and start traversing through that vertex again.

Depth First Search (DFS)

The Depth-First Search (DFS) is a graph traversal algorithm. In this algorithm, one starting vertex is given, and when an adjacent vertex is found, it moves to that adjacent vertex first and tries to traverse in the same manner. It moves through the whole depth, as much as it can go, after that it backtracks to reach previous vertices to find the new path.

To implement DFS in an iterative way, we need to use the stack data structure. If we want to do it recursively, external stacks are not needed, it can be done internal stacks for the recursion calls.

Updated on: 10-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements