Quick actions

cmd+k|ctrl+k

Navigation

Languages

Breadth-First Graph Traversal

Snippet info

Language

Python

Visibility

public

Author

apizzimenti

Created

2016-03-16T21:00:54Z

Updated

2016-03-17T02:13:02Z

'''
returns the shortest path from a root node to a target node.
'''


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

def bfs(g, root, target):
    q = [[root]]
    visited = set()
    
    while q:
        path = q.pop(0)
        vertex = path[-1]
        
        if vertex == target:
            return path
        elif vertex not in visited:
            for node in g.get(vertex, []):
                adj_path = list(path)
                adj_path.append(node)
                q.append(adj_path)
                
            visited.add(vertex)

print(bfs(graph, 0, 6))
INFO