22. DFS (Depth-First Search)
Description
Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking and exploring other paths. DFS is used for a variety of tasks, such as checking graph connectivity, finding connected components, detecting cycles in a graph, and serving as a building block for various advanced graph algorithms.
Key Features:
- Operating Principle: The algorithm starts at an initial vertex and travels along edges to its neighbors, going deeper into the graph. When it can no longer go deeper, it backtracks to explore other branches.
- Visiting Order: All reachable vertices down a single path are explored to their end (or until a dead end is reached) before exploring alternative branches.
Applications of DFS
- Checking graph connectivity.
- Finding connected components in undirected graphs.
- Detecting cycles in directed and undirected graphs.
- Performing topological sorting in directed acyclic graphs (DAGs).
- Solving pathfinding problems, such as finding all possible paths between two vertices.
DFS Algorithm Steps
- Start at vertex
sand mark it as visited.
- For each unvisited neighboring vertex, recursively call DFS.
- The algorithm terminates when all vertices reachable from the start vertex have been visited.
Unlike BFS, which uses a Queue (FIFO), DFS usually utilizes recursion or an explicit Stack (LIFO) to dive deep into graph branches before backtracking.
Example
Consider the following graph:
0
/ \
1 2
\ / \
3 4 5
Adjacency list representation:
graph = {
0: [1, 2],
1: [0, 3],
2: [0, 4, 5],
3: [1],
4: [2],
5: [2]
}
Python Implementation
def dfs(graph, vertex, visited=None):
if visited is None:
visited = set()
visited.add(vertex)
print(vertex, end=" ")
for neighbor in graph[vertex]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
Code Explanation
- We start with a target starting vertex (e.g.,
0).
- The
dfsfunction accepts the currentvertexto explore and avisitedset tracking visited nodes to prevent infinite loops.
- Whenever a vertex is visited, we process it (e.g., print its value).
- We then recursively invoke
dfson all unvisited neighbors.
Complexity of DFS
- Time Complexity: O(V + E), where
Vis the number of vertices andEis the number of edges. Each vertex and edge is visited at most once.
- Space Complexity: O(V), required for storing visited nodes and the call stack during recursive execution (or an explicit stack).
Practical Applications of DFS
- Checking Connectivity:
- To check if a graph is connected, launch DFS from an arbitrary vertex. If all vertices in the graph are marked as visited after the traversal, the graph is connected.
- Finding Connected Components:
- If a graph is disconnected, run DFS repeatedly on each unvisited vertex to identify all separate connected components.
- Cycle Detection in Graphs:
- DFS easily identifies cycles (especially in directed graphs) using recursion call tracking (e.g., distinguishing vertices as unvisited, currently processing, or fully processed). Finding a neighbor that is currently processing indicates a back-edge (cycle).
- Topological Sort:
- In Directed Acyclic Graphs (DAGs), DFS can be used to order vertices linearly according to edge directions by adding nodes to the result list upon finishing their recursive calls.
Problem Example: Detecting Cycles in a Directed Graph
We can use DFS to detect cycles in a directed graph by tracking the recursion stack (rec_stack):
def has_cycle(graph):
visited = set() # Set to track visited vertices
rec_stack = set() # Set to track vertices in the current recursion stack
def dfs_cycle(v):
visited.add(v)
rec_stack.add(v)
for neighbor in graph[v]:
if neighbor not in visited:
if dfs_cycle(neighbor):
return True
elif neighbor in rec_stack:
return True
rec_stack.remove(v)
return False
# Run DFS from every unvisited vertex
for vertex in graph:
if vertex not in visited:
if dfs_cycle(vertex):
return True
return False
# Example Usage
graph_with_cycle = {
0: [1],
1: [2],
2: [0] # Cycle: 0 -> 1 -> 2 -> 0
}
graph_without_cycle = {
0: [1],
1: [2],
2: []
}
print("Graph with cycle:", has_cycle(graph_with_cycle)) # Output: True
print("Graph without cycle:", has_cycle(graph_without_cycle)) # Output: False
Conclusion
DFS is a versatile and essential algorithm for graph traversal. It is heavily utilized for cycle detection, topological sorting, and exploring all deep branches of a search space before backtracking. Its simplicity and recursive nature make it a fundamental technique in computer science and algorithm design.
All rights remain with the original author (Archiveskk). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me