Quick actions

cmd+k|ctrl+k

Navigation

Languages

Depth-First Graph Traversal

Snippet info

Language

Python

Visibility

public

Author

apizzimenti

Created

2016-03-16T21:08:35Z

Updated

2016-03-17T19:06:15Z


'''
Prints the shortest path to the target node.
'''

graph = {
    0: [1, 2, 3],
    1: [4, 5],
    2: [6, 7]
}

visited = []
    
def dfs(g, start, target, path):
    visited.append(start)
    
    if start == target:
        return path + ' ' + str(start)
    else:
        for node in g.get(start, []):
            if node not in visited:
                p = dfs(g, node, target, path + ' ' + str(start))
                
                if p:
                    return p
                
print(dfs(graph, 0, 5, ""))
print(visited)
INFO