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]]
Output: 1 0 2 3 4
Explanation: The source vertex s is 1. We visit it first, then we visit an adjacent.
Start at 1: Mark as visited. Output: 1
Move to 0: Mark as visited. Output: 0 (backtrack to 1)
Move to 2: Mark as visited. Output: 2 (backtrack to 0)
Move to 3: Mark as visited. Output: 3 (backtrack to 2)
Move to 4: Mark as visited. Output: 4 (backtrack to 2)
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]]
Output: 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