Lecture
Depth First Search (DFS) Implementation
1. Using Stack
- DFS uses a stack to keep track of nodes that have been visited. Recursive calls can inherently implement the stack.
Example using Stack
def dfs(graph, start, visited=[]): if start not in visited: visited.append(start) for next in graph[start]: if next not in visited: dfs(graph, next, visited) return visited
2. Recursive Search
- From the current node, look for adjacent nodes that haven't been visited and continue the search.
Example of Recursive Search
for next in graph[start]: if next not in visited: dfs(graph, next, visited)
Time Complexity
-
Time Complexity: (O(V + E))- Here,
Vis the number of vertices, andEis the number of edges. Each vertex is visited once, and each edge is checked twice (in both directions).
- Here,
-
Efficiency in Acyclic Graphs: DFS is effective for visiting all nodes in acyclic graphs. -
Caution in Cyclic Graphs: In graphs with cyclic paths, there's a risk of falling into an infinite loop, so additional mechanisms might be needed to prevent this.
Lessons in this chapter · Graph Data Structures and Greedy Algorithms
- 1. What is a Graph?
- 2. Graph Implementation Techniques
- 3. Multiple-choice quiz
- 4. What is Depth First Search (DFS)?
- 5. Depth First Search (DFS) Implementation
- 6. Coding Quiz - Visit Order (DFS)
- 7. What is Breadth-First Search (BFS)?
- 8. Breadth-First Search (BFS) Implementation Guide
- 9. Coding Quiz - Order of Visits (BFS)
- 10. What are Greedy Algorithms?
- 11. Greedy Algorithm Implementation Guide
- 12. Multiple-choice quiz
- 13. Coding Quiz - ATM Problem
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help