ComputeDepth-First Search (DFS) in Python

Nkugwa Mark William
2 min readFeb 5, 2023

--

Depth-First Search (DFS) is a method for traversing a graph or tree data structure by visiting all the vertices or nodes as deep as possible before backtracking. DFS can be implemented using a stack or recursion. Here is an example implementation using recursion:

graph = {0: [1, 2], 1: [2], 2: [0, 3], 3: []}
visited = set()

def dfs(start):
print(start, end=" ")
visited.add(start)
for node in graph[start]:
if node not in visited:
dfs(node)

if __name__ == "__main__":
# Example graph
dfs(2) # Output: 2 0 1 3

Explanation:

  1. The graph dictionary represents the adjacency list of the graph, where graph[i] is a list of nodes that node i is connected to.
  2. The visited set is used to keep track of which nodes have been visited during the DFS.
  3. The dfs function takes a starting node as input and performs the DFS.
  4. In the dfs function, the starting node is printed and added to the visited set.
  5. The for loop checks if there is an edge between the current node and an unvisited node. If there is, the dfs function is called for that node.
  6. The if __name__ == "__main__" block is a special Python construct that only executes the code inside if the script is run directly (not imported as a module).
  7. In the main block, the example graph is initialized, and the DFS is started from node 2.

--

--

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