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


Dijkstra's Single Source Shortest Path Algorithm

Shortest path in Undirected Graph with unit weights

Detect cycle in an undirected graph

Graph representation in Java (Matrix and List)

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

Check whether a given graph is Bipartite or not

Breadth First Search or BFS for a Graph

Bellman-Ford Algorithm - Shortest Distance with Negative Edge

Topological Sorting (Using BFS or DFS)

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