Depth-first search explained in python
Depth First Search (DFS) is a popular algorithm for traversing and searching a graph or tree data structure. It involves starting at the root node (or any arbitrary node) and exploring as far as possible along each branch before backtracking. Here’s a simple implementation of DFS in Python:
def DFS(graph, node, visited):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
DFS(graph, neighbor, visited)
graph = {0: [1, 2], 1: [2], 2: []}
visited = set()
DFS(graph, 0, visited)
print(visited)
Explanation:
- A function
DFS
is defined, which takes a graph represented as an adjacency list, a starting node and a set of visited nodes. - The function adds the starting node to the visited set.
- For each neighbor of the current node, it checks if the neighbor has not been visited yet.
- If the neighbor has not been visited, it calls the
DFS
function with the neighbor as the new starting node. - This process is repeated until all nodes connected to the starting node have been visited.
- Finally, the
visited
set is printed to show the nodes visited by the DFS algorithm.
An analogy for DFS could be imagine you are exploring a maze, you start at the entrance and take the first path you encounter, you keep going down that path until you reach a dead end, then you backtrack to the last fork and take the next path, you repeat this process until you reach the end of the maze.
Limitations: DFS can be very inefficient in terms of memory usage as it involves exploring long branches before backtracking, which can lead to a large number of function calls being stored on the call stack. Additionally, it may not be the best choice for finding the shortest path in a graph as it does not prioritize visiting nodes that are closer to the goal.