01. DFS of graph
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To perform a Depth-First Search (DFS) of a graph, we start by visiting the starting node and then recursively visit all its adjacent unvisited nodes. We use a recursive function to traverse the graph in a depth-first manner.
Here are the steps of the DFS algorithm:
Create a function dfs
that takes the current node, an output vector to store the traversal order, an adjacency list representing the graph, and a visited array to keep track of visited nodes.
Add the current node to the output vector to record the traversal order.
Mark the current node as visited.
For each unvisited adjacent node of the current node, call the dfs
function recursively with that node.
Once we have traversed all nodes reachable from the starting node, the dfsOfGraph
function will return the output vector containing the DFS traversal order.
Time Complexity: In the worst case, it traverses all the nodes and edges, resulting in a time complexity of O(V + E)
, where V
is the number of nodes (vertices) and E
is the number of edges in the graph.
Auxiliary Space Complexity: O(V)
as we use an additional visited array of size V
to keep track of visited nodes. Additionally, the output vector to store the traversal order also requires O(V)
space.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the repository.