-
Notifications
You must be signed in to change notification settings - Fork 0
DepthFirstSearch
krishanthan4 edited this page Dec 16, 2025
·
1 revision
Implement depth-first search for graph traversal. DFS explores as far as possible along each branch before backtracking.
DFS is a graph traversal algorithm that explores a graph by going as deep as possible down each path before backtracking.
- Time Complexity: O(V + E) where V is vertices and E is edges
- Space Complexity: O(V) for the visited set and stack/recursion
- Traversal Strategy: Go deep first, then backtrack
- Implementation: Stack (iterative) or Recursion
- Start at a given node
- Mark it as visited
- Visit one of its unvisited neighbors
- Repeat step 3 recursively/iteratively
- Backtrack when no unvisited neighbors remain
Implement the following methods in Depth_First_Search.java:
-
dfs(Map<Integer, List<Integer>> graph, int start)- Iterative DFS using a stack -
dfsRecursive(Map<Integer, List<Integer>> graph, int start)- Recursive DFS -
dfsRecursiveHelper(...)- Helper method for recursion
The graph is represented as an adjacency list:
Map<Integer, List<Integer>>
Key: vertex
Value: list of adjacent vertices
- Single node graph
- Disconnected graph (some nodes unreachable from start)
- Cyclic graph
- Linear graph (like a linked list)
- Complete graph (all nodes connected)
- Use a Set to track visited nodes
- For iterative: Use a Stack (LIFO)
- For recursive: Use the call stack naturally
- Process a node when you visit it, not when you pop it
- Finding connected components
- Topological sorting
- Detecting cycles
- Maze solving
- Puzzle solving
- How would you detect a cycle using DFS?
- How would you find all paths between two nodes?
- What's the difference between DFS and BFS in terms of when you'd use each?
- How would you implement DFS for a tree vs. a graph?
- Forgetting to mark nodes as visited (causes infinite loops)
- Not handling disconnected graphs
- Stack overflow in recursive implementation for very deep graphs
- Breadth First Search (BFS)
- Topological Sort
- Strongly Connected Components (Tarjan's/Kosaraju's)