Depth-First Traversal (DFS) for a graph

Posted by 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


Check whether a given graph is Bipartite or not

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

Topological Sorting (Using BFS or DFS)

Detect cycle in an undirected graph

Dijkstra's Single Source Shortest Path Algorithm

Graph representation in Java (Matrix and List)

Bellman-Ford Algorithm - Shortest Distance with Negative Edge

Shortest path in Undirected Graph with unit weights

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

Breadth First Search or BFS for a Graph