![]() |
VOOZH | about |
Given a directed Graph, the task is to perform Depth First Search of the given graph.
Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.
Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick vertices as per the insertion order.
Input: adj = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]
👁 Input_undirected_GraphOutput: [0 1 2 3 4]
Explanation: The source vertex s is 0. We visit it first, then we visit an adjacent.
Start at 0: Mark as visited. Output: 0
Move to 1: Mark as visited. Output: 1
Move to 2: Mark as visited. Output: 2
Move to 3: Mark as visited. Output: 3 (backtrack to 2)
Move to 4: Mark as visited. Output: 4 (backtrack to 2, then backtrack to 1, then to 0)Not that there can be more than one DFS Traversals of a Graph. For example, after 1, we may pick adjacent 2 instead of 0 and get a different DFS. Here we pick in the insertion order.
Input: [[2,3,1], [0], [0,4], [0], [2]]
👁 Input_undirected_Graph2Output: [0 2 4 3 1]
Explanation: DFS Steps:Start at 0: Mark as visited. Output: 0
Move to 2: Mark as visited. Output: 2
Move to 4: Mark as visited. Output: 4 (backtrack to 2, then backtrack to 0)
Move to 3: Mark as visited. Output: 3 (backtrack to 0)
Move to 1: Mark as visited. Output: 1 (backtrack to 0)
The recursive implementation of DFS is already discussed: Depth First Search or DFS for a Graph.
The idea is to fist push the given source into the stack. Then keep popping items from the stack while stack has items. Once we pop an item, we add it to the result and then push all its adjacent into the stack in reverse order. Please note that the last added item is going to be removed first.
Step by step approach:
0 1 2 3
The above solution works only for connected graph. In this approach, the idea is to ensure that all nodes are visited. If a node is unvisited, start DFS from this node.
0 1 2 3