|
| 1 | +# Python3 Program to print BFS traversal |
| 2 | +# from a given source vertex. BFS(int s) |
| 3 | +# traverses vertices reachable from s. |
| 4 | +from collections import defaultdict |
| 5 | + |
| 6 | +# This class represents a directed graph |
| 7 | +# using adjacency list representation |
| 8 | +class Graph: |
| 9 | + |
| 10 | + # Constructor |
| 11 | + def __init__(self): |
| 12 | + |
| 13 | + # default dictionary to store graph |
| 14 | + self.graph = defaultdict(list) |
| 15 | + |
| 16 | + # function to add an edge to graph |
| 17 | + def addEdge(self,u,v): |
| 18 | + self.graph[u].append(v) |
| 19 | + |
| 20 | + # Function to print a BFS of graph |
| 21 | + def BFS(self, s): |
| 22 | + |
| 23 | + # Mark all the vertices as not visited |
| 24 | + visited = [False] * (len(self.graph)) |
| 25 | + |
| 26 | + # Create a queue for BFS |
| 27 | + queue = [] |
| 28 | + |
| 29 | + # Mark the source node as |
| 30 | + # visited and enqueue it |
| 31 | + queue.append(s) |
| 32 | + visited[s] = True |
| 33 | + |
| 34 | + while queue: |
| 35 | + |
| 36 | + # Dequeue a vertex from |
| 37 | + # queue and print it |
| 38 | + s = queue.pop(0) |
| 39 | + print (s, end = " ") |
| 40 | + |
| 41 | + # Get all adjacent vertices of the |
| 42 | + # dequeued vertex s. If a adjacent |
| 43 | + # has not been visited, then mark it |
| 44 | + # visited and enqueue it |
| 45 | + for i in self.graph[s]: |
| 46 | + if visited[i] == False: |
| 47 | + queue.append(i) |
| 48 | + visited[i] = True |
| 49 | + |
| 50 | +# Driver code |
| 51 | + |
| 52 | +# Create a graph given in |
| 53 | +# the above diagram |
| 54 | +g = Graph() |
| 55 | +g.addEdge(0, 1) |
| 56 | +g.addEdge(0, 2) |
| 57 | +g.addEdge(1, 2) |
| 58 | +g.addEdge(2, 0) |
| 59 | +g.addEdge(2, 3) |
| 60 | +g.addEdge(3, 3) |
| 61 | + |
| 62 | +print ("Following is Breadth First Traversal" |
| 63 | + " (starting from vertex 2)") |
| 64 | +g.BFS(2) |
| 65 | + |
| 66 | +# This code is contributed by Neelam Yadav |
0 commit comments