- Asked 4/14
- 2074 Bhadra · 4 marks
- 2070 Bhadra · 5 marks
Depth first traversal in graph
Short answer
Depth-first traversal explores as far as possible along a branch before backtracking, using a stack or recursion. For example, starting at A in graph A-B, A-C, B-D, B-E, C-F, E-F, DFS order is A B D E F C. Complexity O(V+E).
Explain Depth first traversal in graph with example.
Depth first traversal (DFS) visits the vertices of a graph by going as deep as possible along a path before backtracking. It starts from a source vertex, marks it visited, then moves to an unvisited neighbour, and continues until a vertex has no unvisited neighbour; then it backtracks to the previous vertex and tries the next neighbour. It uses a stack (or recursion).
Algorithm (using a stack)
DFS(G, start)
1. push start on stack, mark start visited, print it
2. while stack not empty
3. v = top of stack
4. if v has an unvisited neighbour w
5. mark w visited, print w, push w
6. else pop stack // backtrack
Recursive version:
int adj[N][N], visited[N], n;
void dfs(int v) {
visited[v] = 1;
printf("%d ", v);
for (int w = 0; w < n; w++)
if (adj[v][w] && !visited[w])
dfs(w);
}
Example
A
/ \
B C
/ \ \
D E---F
Edges: A-B, A-C, B-D, B-E, C-F, E-F. Adjacency lists (alphabetical): A: B, C; B: A, D, E; C: A, F; D: B; E: B, F; F: C, E.
Start at A, choosing neighbours in alphabetical order:
| Step | Current | Action | Stack (bottom to top) | Visited order |
|---|---|---|---|---|
| 1 | A | visit A | A | A |
| 2 | B | visit B | A B | A B |
| 3 | D | visit D | A B D | A B D |
| 4 | D | no new neighbour, pop | A B | A B D |
| 5 | E | visit E | A B E | A B D E |
| 6 | F | visit F | A B E F | A B D E F |
| 7 | C | visit C (from F) | A B E F C | A B D E F C |
| 8 | - | all visited, pop until empty |
DFS order: A B D E F C
Complexity: O(V + E) with adjacency lists, O(V²) with an adjacency matrix. Uses: cycle detection, topological sort, connected components, path finding.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- BFS and DFS with example · Data Structure and Algorithm, chapter 10 · asked 4×
- Breadth first traversal in graph · Data Structure and Algorithm, chapter 10 · asked 2×