fork download
  1. def func():
  2.  
  3. def bfs(node):
  4. Q = [ 0 ] * ( nodes + 1 )
  5. first = 0
  6. last = 0
  7. explored = [0] * (nodes+1)
  8. Q[first] = node
  9. explored[node] = 1
  10.  
  11. while first <= last:
  12. vertex = Q[first]
  13. k = 0
  14. while k < nodes+1:
  15. if matrix[vertex][k] == 1 and explored[k] == 0:
  16. explored[k] = 1
  17. last+=1
  18. Q[last] = k
  19. k+=1
  20. first+=1
  21.  
  22. for i in range(0, nodes):
  23. print(Q[i], end=" ")
  24.  
  25. line = input().split(" ")
  26. nodes = int(line[0])
  27. edges = int(line[1])
  28. matrix = [[0 for column in range(nodes+1)] for row in range(nodes+1)]
  29. for k in range(0, edges):
  30. line = [int(i) for i in input().split(" ")]
  31. x = int(line[0])
  32. y = int(line[1])
  33. matrix[x][y] = 1
  34.  
  35. startNode = 1
  36. bfs(startNode)
  37. func()
Success #stdin #stdout 0.05s 9776KB
stdin
9 8
1 2
1 3
3 4
3 5
5 9
4 6
4 7
4 8
stdout
1 2 3 4 5 6 7 8 9