Depth-first search python

Python -- Posted on April 9, 2018

Depth-first search python

              
                def dfs(graph, vertex):
    output = []
    if isinstance(graph, dict):
        visited = {key: False for key in graph.keys()}
    if isinstance(graph, list):
        visited = [False] * len(graph)
    stack = []
    stack.append(vertex)
    while stack:
        v = stack.pop()
        if not visited[v]:
            visited[v] = True
            output.append(v)
            for neighbor in graph[v]:
                stack.append(neighbor)
    return output
                  
   
            

Related Posts