Advertisement
nq1s788

BFS

Feb 14th, 2024
1,099
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. from queue import Queue
  2. n, m = map(int, input().split()) #n - кол-во вершин, m - кол-во ребер
  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 = [-1] * n
  11. used[0] = 0
  12. q = Queue()
  13. q.put(0)
  14. while not q.empty():
  15.     h = q.get() #h - текущая вершина
  16.     for e in g[h]:
  17.         if used[e] == -1:
  18.             used[e] = used[h] + 1
  19.             q.put(e)
  20. end = int(input())
  21. print(used[end - 1], used)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement