| 4 | |
| 5 | |
| 6 | class Graph: |
| 7 | def __init__(self): |
| 8 | self.vertex = {} |
| 9 | |
| 10 | # for printing the Graph vertices |
| 11 | def print_graph(self) -> None: |
| 12 | """ |
| 13 | Print the graph vertices. |
| 14 | |
| 15 | Example: |
| 16 | >>> g = Graph() |
| 17 | >>> g.add_edge(0, 1) |
| 18 | >>> g.add_edge(0, 2) |
| 19 | >>> g.add_edge(1, 2) |
| 20 | >>> g.add_edge(2, 0) |
| 21 | >>> g.add_edge(2, 3) |
| 22 | >>> g.add_edge(3, 3) |
| 23 | >>> g.print_graph() |
| 24 | {0: [1, 2], 1: [2], 2: [0, 3], 3: [3]} |
| 25 | 0 -> 1 -> 2 |
| 26 | 1 -> 2 |
| 27 | 2 -> 0 -> 3 |
| 28 | 3 -> 3 |
| 29 | """ |
| 30 | print(self.vertex) |
| 31 | for i in self.vertex: |
| 32 | print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]])) |
| 33 | |
| 34 | # for adding the edge between two vertices |
| 35 | def add_edge(self, from_vertex: int, to_vertex: int) -> None: |
| 36 | """ |
| 37 | Add an edge between two vertices. |
| 38 | |
| 39 | :param from_vertex: The source vertex. |
| 40 | :param to_vertex: The destination vertex. |
| 41 | |
| 42 | Example: |
| 43 | >>> g = Graph() |
| 44 | >>> g.add_edge(0, 1) |
| 45 | >>> g.add_edge(0, 2) |
| 46 | >>> g.print_graph() |
| 47 | {0: [1, 2]} |
| 48 | 0 -> 1 -> 2 |
| 49 | """ |
| 50 | # check if vertex is already present, |
| 51 | if from_vertex in self.vertex: |
| 52 | self.vertex[from_vertex].append(to_vertex) |
| 53 | else: |
| 54 | # else make a new vertex |
| 55 | self.vertex[from_vertex] = [to_vertex] |
| 56 | |
| 57 | def dfs(self) -> None: |
| 58 | """ |
| 59 | Perform depth-first search (DFS) traversal on the graph |
| 60 | and print the visited vertices. |
| 61 | |
| 62 | Example: |
| 63 | >>> g = Graph() |
no outgoing calls
no test coverage detected