|
| 1 | +# Author: OMKAR PATHAK |
| 2 | + |
| 3 | +class Graph(): |
| 4 | + def __init__(self): |
| 5 | + self.vertex = {} |
| 6 | + |
| 7 | + # for printing the Graph vertexes |
| 8 | + def printGraph(self): |
| 9 | + for i in self.vertex.keys(): |
| 10 | + print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) |
| 11 | + |
| 12 | + # for adding the edge beween two vertexes |
| 13 | + def addEdge(self, fromVertex, toVertex): |
| 14 | + # check if vertex is already present, |
| 15 | + if fromVertex in self.vertex.keys(): |
| 16 | + self.vertex[fromVertex].append(toVertex) |
| 17 | + else: |
| 18 | + # else make a new vertex |
| 19 | + self.vertex[fromVertex] = [toVertex] |
| 20 | + |
| 21 | + def BFS(self, startVertex): |
| 22 | + # Take a list for stoting already visited vertexes |
| 23 | + visited = [False] * len(self.vertex) |
| 24 | + |
| 25 | + # create a list to store all the vertexes for BFS |
| 26 | + queue = [] |
| 27 | + |
| 28 | + # mark the source node as visited and enqueue it |
| 29 | + visited[startVertex] = True |
| 30 | + queue.append(startVertex) |
| 31 | + |
| 32 | + while queue: |
| 33 | + startVertex = queue.pop(0) |
| 34 | + print(startVertex, end = ' ') |
| 35 | + |
| 36 | + # mark all adjacent nodes as visited and print them |
| 37 | + for i in self.vertex[startVertex]: |
| 38 | + if visited[i] == False: |
| 39 | + queue.append(i) |
| 40 | + visited[i] = True |
| 41 | + |
| 42 | +if __name__ == '__main__': |
| 43 | + g = Graph() |
| 44 | + g.addEdge(0, 1) |
| 45 | + g.addEdge(0, 2) |
| 46 | + g.addEdge(1, 2) |
| 47 | + g.addEdge(2, 0) |
| 48 | + g.addEdge(2, 3) |
| 49 | + g.addEdge(3, 3) |
| 50 | + |
| 51 | + g.printGraph() |
| 52 | + print('BFS:') |
| 53 | + g.BFS(2) |
| 54 | + |
| 55 | + # OUTPUT: |
| 56 | + # 0 -> 1 -> 2 |
| 57 | + # 1 -> 2 |
| 58 | + # 2 -> 0 -> 3 |
| 59 | + # 3 -> 3 |
| 60 | + # BFS: |
| 61 | + # 2 0 3 1 |
0 commit comments