Skip to content

Instantly share code, notes, and snippets.

@meetzaveri
Created June 17, 2018 07:48
Show Gist options
  • Save meetzaveri/2589cdb2e8c48b130504f576388da227 to your computer and use it in GitHub Desktop.
Save meetzaveri/2589cdb2e8c48b130504f576388da227 to your computer and use it in GitHub Desktop.
import collections
def bfs(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1,2]}
breadth_first_search(graph, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment