πDay 1. DFS of Graph π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a connected undirected graph represented by a 2D adjacency list adj[][], where adj[i] represents the list of vertices connected to vertex i.
Perform a Depth First Search (DFS) traversal starting from vertex 0, visiting vertices from left to right as per the given adjacency list.
Return a list containing the DFS traversal of the graph.
Note: Traverse nodes in the same order as given in the adjacency list.
Note: Sorry for uploading late, my exam is going on.
π Example Walkthrough:
Example 1:
Input:
adj = [[2, 3, 1],
[0],
[0, 4],
[0],
[2]]Output:
Explanation:
The DFS traversal proceeds as follows:
Start at vertex
0β Output:[0]Visit
2(first neighbor of0) β Output:[0, 2]Visit
4(first neighbor of2) β Output:[0, 2, 4]Backtrack to
2, then backtrack to0, visit3β Output:[0, 2, 4, 3]Backtrack to
0and visit1β Final Output:[0, 2, 4, 3, 1]
Example 2:
Input:
Output:
Explanation:
The DFS traversal proceeds as follows:
Start at vertex
0β Output:[0]Visit
1(first neighbor of0) β Output:[0, 1]Visit
2(first neighbor of1) β Output:[0, 1, 2]Visit
3(first neighbor of2) β Output:[0, 1, 2, 3]Backtrack to
2and visit4β Final Output:[0, 1, 2, 3, 4]
Constraints:
$1 \leq$
adj.size()$\leq 10^4$$1 \leq$
adj[i][j]$\leq 10^4$
π― My Approach:
Recursive DFS (Using Lambda Function)
Algorithm Steps:
Maintain a visited array to track visited nodes.
Implement DFS using recursion and a lambda function.
Start DFS traversal from node
0and recursively visit neighbors in the given order.If a node is unvisited, continue DFS.
Store the DFS traversal sequence in a list.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(V + E), since each vertex and edge is visited once.
Expected Auxiliary Space Complexity: O(V), as we store the visited array and recursive function calls.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated