Depth-first search explained in python

Nkugwa Mark William
2 min readFeb 11, 2023

--

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:

  1. A function DFS is defined, which takes a graph represented as an adjacency list, a starting node and a set of visited nodes.
  2. The function adds the starting node to the visited set.
  3. For each neighbor of the current node, it checks if the neighbor has not been visited yet.
  4. If the neighbor has not been visited, it calls the DFS function with the neighbor as the new starting node.
  5. This process is repeated until all nodes connected to the starting node have been visited.
  6. 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.

--

--

Nkugwa Mark William
Nkugwa Mark William

Written by Nkugwa Mark William

Nkugwa Mark William is a Chemical and Process engineer , entrepreneur, software engineer and a technologists with Apps on google play store and e commerce sites

No responses yet