| 6 | |
| 7 | |
| 8 | class Graph(): |
| 9 | def __init__(self): |
| 10 | self.vertex = {} |
| 11 | |
| 12 | # for printing the Graph vertexes |
| 13 | def printGraph(self): |
| 14 | print(self.vertex) |
| 15 | for i in self.vertex.keys(): |
| 16 | print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) |
| 17 | |
| 18 | # for adding the edge beween two vertexes |
| 19 | def addEdge(self, fromVertex, toVertex): |
| 20 | # check if vertex is already present, |
| 21 | if fromVertex in self.vertex.keys(): |
| 22 | self.vertex[fromVertex].append(toVertex) |
| 23 | else: |
| 24 | # else make a new vertex |
| 25 | self.vertex[fromVertex] = [toVertex] |
| 26 | |
| 27 | def DFS(self): |
| 28 | # visited array for storing already visited nodes |
| 29 | visited = [False] * len(self.vertex) |
| 30 | |
| 31 | # call the recursive helper function |
| 32 | for i in range(len(self.vertex)): |
| 33 | if visited[i] == False: |
| 34 | self.DFSRec(i, visited) |
| 35 | |
| 36 | def DFSRec(self, startVertex, visited): |
| 37 | # mark start vertex as visited |
| 38 | visited[startVertex] = True |
| 39 | |
| 40 | print(startVertex, end = ' ') |
| 41 | |
| 42 | # Recur for all the vertexes that are adjacent to this node |
| 43 | for i in self.vertex.keys(): |
| 44 | if visited[i] == False: |
| 45 | self.DFSRec(i, visited) |
| 46 | |
| 47 | if __name__ == '__main__': |
| 48 | g = Graph() |