|
| 1 | +class Graph: |
| 2 | + def __init__(self): |
| 3 | + self.path = [] |
| 4 | + self.vertices = [] |
| 5 | + self.neighbors = [] |
| 6 | + |
| 7 | + def add_node(self, number, neighbors): |
| 8 | + self.vertices.append(number) |
| 9 | + self.neighbors.append(neighbors) |
| 10 | + self.path.append(0) |
| 11 | + |
| 12 | + # 0 - white, 1 - grey, 2 - black |
| 13 | + def BFS(self, start): |
| 14 | + color = [0] * len(self.vertices) |
| 15 | + distance = [0] * len(self.vertices) |
| 16 | + queue = [] |
| 17 | + for vert in self.vertices: |
| 18 | + if vert != start: |
| 19 | + color[vert] = 0 |
| 20 | + self.path[vert] = None |
| 21 | + color[start] = 1 |
| 22 | + distance[start] = 0 |
| 23 | + self.path[start] = None |
| 24 | + queue.append(start) |
| 25 | + while len(queue) != 0: |
| 26 | + u = queue.pop(0) |
| 27 | + for vert in self.neighbors[u]: |
| 28 | + if color[vert] == 0: |
| 29 | + color[vert] = 1 |
| 30 | + distance[vert] = distance[u] + 1 |
| 31 | + self.path[vert] = u |
| 32 | + queue.append(vert) |
| 33 | + color[u] = 2 |
| 34 | + |
| 35 | + def DFS(self, start): |
| 36 | + visited = [False] * (len(self.vertices)) |
| 37 | + self.DFS_move(start, visited) |
| 38 | + |
| 39 | + def DFS_move(self, vert, visited): |
| 40 | + visited[vert] = True |
| 41 | + print(vert, end=' ') |
| 42 | + |
| 43 | + for adj in self.neighbors[vert]: |
| 44 | + if visited[adj] == False: |
| 45 | + self.DFS_move(adj, visited) |
| 46 | + |
| 47 | + def print_path(self, start, end): |
| 48 | + if start == end: |
| 49 | + print(start) |
| 50 | + elif self.path[end] == None: |
| 51 | + print("Path from " + str(start) + " to " + |
| 52 | + str(end) + " doesn't exist!") |
| 53 | + else: |
| 54 | + self.print_path(start, self.path[end]) |
| 55 | + print(str(end) + " ") |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + g = Graph() |
| 60 | + g.add_node(0, [1]) |
| 61 | + g.add_node(1, [0, 2, 3]) |
| 62 | + g.add_node(2, [1, 3, 5]) |
| 63 | + g.add_node(3, [1, 2, 4]) |
| 64 | + g.add_node(4, [3, 5]) |
| 65 | + g.add_node(5, [2, 4, 6]) |
| 66 | + g.add_node(6, [5]) |
| 67 | + g.BFS(0) |
| 68 | + g.print_path(0, 6) |
| 69 | + g.DFS(4) |
0 commit comments