fork download
  1. def CreateMatrix(NumNodes, Edges):
  2. Matrix = [[0 for i in range(NumNodes)] for j in range(NumNodes)]
  3.  
  4. for edge in Edges:
  5. A=edge[0]
  6. B=edge[1]
  7. Matrix[A][B]=1
  8. Matrix[B][A]=1
  9.  
  10. return Matrix
  11.  
  12. def CountNeighbors(Matrix, Node):
  13. cnt = 0
  14. for i in range(len(Matrix[Node])):
  15. if Matrix[Node][i]==1:
  16. cnt+=1
  17. return cnt
  18.  
  19.  
  20. def BreadthFirst(Matrix, Start):
  21. visited = [False] * len(Matrix)
  22. result = []
  23. queue = [Start]
  24.  
  25. visited[Start] = True
  26. result.append(Start)
  27.  
  28. while len(queue) > 0:
  29. current = queue.pop(0)
  30.  
  31. for i in range(len(Matrix[current])):
  32. if Matrix[current][i] == 1 and visited[i] == False:
  33. visited[i] = True
  34. result.append(i)
  35. queue.append(i)
  36.  
  37. return result
  38.  
  39. Edges = [[0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 5]]
  40. Matrix = CreateMatrix(6, Edges)
  41.  
  42. print(CountNeighbors(Matrix, 0))
  43. print(BreadthFirst(Matrix, 0))
  44. print(BreadthFirst(Matrix, 3))
  45.  
Success #stdin #stdout 0.04s 63640KB
stdin
Standard input is empty
stdout
2
[0, 1, 2, 3, 4, 5]
[3, 1, 5, 0, 4, 2]