图之广度遍历

141 阅读1分钟
#!/usr/bin/env python2.7
# -*- conding: utf-8 -*-
# @Time : 2020/10/14 20:23
# @Author : ada
# @file : bfs.py.py
# @Project: python-script 
import Queue

def bfs(adj,start):
    visited = set()
    q = Queue.Queue()
    q.put(start)
    while not q.empty():
        u = q.get()
        print(u)
        for v in adj.get(u,[]):
            if v not in visited:
                visited.add(v)
                q.put(v)

graph = {1:[4,2],2:[3,4],3:[4],4:[5]}
bfs(graph,1)