Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: Implement a depth-first search (DFS) algorithm for a graph.
Answer:

def dfs(graph, node, visited):

  if node not in visited:

    print(node)

    visited.add(node)

    for neighbor in graph[node]:

      dfs(graph, neighbor, visited)

Example:

graph = {1: [2, 3], 2: [4, 5], 3: [6], 4: [], 5: [], 6: []}
visited_set = set()
dfs(graph, 1, visited_set)
Is it helpful? Yes No

Most helpful rated by users:

©2025 WithoutBook