Depth-First Traversal (DFS) for a graph

Posted by N.K. Chauhan on Mar 31, 2024

Given a directed graph in the form of an adjacency list, adj[][] and the count of vertex "v".

The task is to perform a depth-first-traversal (DFS) on this graph starting from "0".


Solutions

Method 1: DFS of Graph

We can perform DFS on a graph easily with the help of recursion.

The idea is to start recursion from the 0-th element - if this has not already been visited, print it and also call the function recursively for all its adjacent elements.

Complexity

The time complexity of this solution is O(v+e) and space complexity is O(v).

Related


Topological Sorting (Using BFS or DFS)

Breadth First Search or BFS for a Graph

Detect cycle in an undirected graph

Check whether a given graph is Bipartite or not

Dijkstra's Single Source Shortest Path Algorithm

Detect Cycle in a Directed Graph (Using BFS or DFS)

Minimum Spanning Tree (Prim's and Kruskal's algorithm)

Graph representation in Java (Matrix and List)

Bellman-Ford Algorithm - Shortest Distance with Negative Edge

Shortest path in Undirected Graph with unit weights