Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.0 KiB

4 years ago
  1. from collections import defaultdict
  2. #--class for directed graph with adjacency list representation
  3. class Graph:
  4. #--Constructor of the class
  5. def __init__(self):
  6. #--default dictionary to store graph
  7. self.graph = defaultdict(list)
  8. '''
  9. --function to add an edge
  10. --inputs, starting point of the graph
  11. '''
  12. def addEdge(self,u,v):
  13. self.graph[u].append(v)
  14. '''
  15. --to print a BFS of graph
  16. --inputs, starting point of the graph
  17. --Prints the BFS starting from the input point
  18. '''
  19. def BFS(self, s):
  20. # Mark all the vertices as not visited
  21. visited = [False] * (len(self.graph))
  22. queue = []
  23. # Mark the source node as visited and enqueue it
  24. queue.append(s)
  25. visited[s] = True
  26. while queue:
  27. s = queue.pop(0)
  28. print (s, end = " ")
  29. for i in self.graph[s]:
  30. if visited[i] == False:
  31. queue.append(i)
  32. visited[i] = True