imashutosh51

BFS

Mar 20th, 2026
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.51 KB | None | 0 0
  1. from collections import deque
  2. class Solution:
  3.     def bfs(self, adj):
  4.         visited={}
  5.         ans=[]
  6.         q=deque([])
  7.         q.append(0)
  8.         visited[0]=True
  9.        
  10.         while len(q)>0:
  11.             k=len(q)
  12.             for i in range(k):
  13.                 temp=q.popleft()
  14.                 ans.append(temp)
  15.                 for k in adj[temp]:
  16.                     if visited.get(k,False)==False:
  17.                         visited[k]=True
  18.                         q.append(k)
  19.         return ans
Advertisement
Add Comment
Please, Sign In to add comment