Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

pythn bfs

def bfs(graph,start):
    visited=[]
    q=[start]
    
    while q:
        print(f"q=",q)
        node=q.pop(0)
        print(f"visited",visited)
        if node not in visited:
            visited.append(node)
            neighbors=graph[node]
           
            for neigh in neighbors:
                q.append(neigh)
    return visited

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

print(bfs(graph,1))

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.