Welcome to our comprehensive guide on Depth First Search (DFS)! In this lesson, we'll delve into the world of graph traversal algorithms, focusing on DFS - a powerful technique used in various real-world applications like route finding, network analysis, and more.
Let's start by understanding what DFS is and why we need it.
DFS is a method for exploring or searching through a graph, starting at a particular node, and visiting the nodes reachable from that node as far as possible before backtracking. The idea is to explore as deeply as possible along each path before backtracking.
The DFS algorithm can be implemented in three main steps:
Let's look at a simple example of DFS implementation in Python.
def dfs(vertex, visited, adj_list):
visited[vertex] = True
print(vertex, end=" ")
for neighbor in adj_list[vertex]:
if not visited[neighbor]:
dfs(neighbor, visited, adj_list)
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
visited = [False] * len(graph)
dfs('A', visited, graph)
print()Output:
A B D E C F
In the above example, we have a simple graph and we perform a DFS starting from vertex 'A'. The output shows the order in which the vertices are visited.
The above example demonstrates the iterative version of DFS. However, DFS can also be implemented recursively. Let's modify the above example to show the recursive DFS implementation.
def dfs_recursive(vertex, visited, adj_list):
visited[vertex] = True
print(vertex, end=" ")
for neighbor in adj_list[vertex]:
if not visited[neighbor]:
dfs_recursive(neighbor, visited, adj_list)
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
visited = [False] * len(graph)
dfs_recursive('A', visited, graph)
print()Output:
A B D E C F
In the recursive version, we avoid the need for a stack, making the code slightly cleaner.
Which of the following statements is true about DFS?
With this, we've covered the basics of DFS. As you continue to explore and practice, you'll encounter more complex scenarios and variations of this powerful graph traversal algorithm. Happy coding! š