DEV Community

Sayani Mallick
Sayani Mallick

Posted on

Depth first search on Graphs

Depth first search on Graphs is a very basic question on graphs and is necessary to solve any graph question of graphs.
A graph is a data structure which is defined in terms of vertices and edges,that is, G=f(V,E).

ALGORITHM
In depth first search, we first mark all the nodes as 'unvisited'. We start from the root of the graph and mark it as visited, and then move on to its connected nodes. If the present node has any unvisited node then we move on to that node. In the absence of any unvisited node, we backtrack and move to another node.

Let us implement the Explore function

Explore(i)
mark all nodes as unvisited

for all i node in graph
{
if node unvisited
mark node as visited
Explore(i)
}

Alt Text

Hope this helps you!

Top comments (0)