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

Graph representation in Java (Matrix and List)

Dijkstra's Single Source Shortest Path Algorithm

Breadth First Search or BFS for a Graph

Detect cycle in an undirected graph

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

Bellman-Ford Algorithm - Shortest Distance with Negative Edge

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

Shortest path in Undirected Graph with unit weights

Topological Sorting (Using BFS or DFS)