Dimitris Kougioumtzis Blog About technology

Depth-first search python

Category Python

Posted on April 9, 2018



Depth-first search python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere