Advertisement
nq1s788

bfs

Apr 9th, 2024
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.40 KB | None | 0 0
  1. from queue import Queue
  2. n, m = map(int, input().split())
  3. g = [[] for i in range(n)]
  4. for i in range(m):
  5.     x, y = map(int, input().split())
  6.     x -= 1
  7.     y -= 1
  8.     g[x].append(y)
  9.     g[y].append(x)
  10. used = [False] * n
  11. q = Queue()
  12. q.put(0)
  13. used[0] = True
  14. while not q.empty():
  15.     cur = q.get()
  16.     for nxt in g[cur]:
  17.         if not used[nxt]:
  18.             used[nxt] = True
  19.             q.put(nxt)
  20.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement