| 2 | |
| 3 | |
| 4 | class Graph: |
| 5 | def __init__(self, vertices: int) -> None: |
| 6 | """ |
| 7 | >>> graph = Graph(2) |
| 8 | >>> graph.vertices |
| 9 | 2 |
| 10 | >>> len(graph.graph) |
| 11 | 2 |
| 12 | >>> len(graph.graph[0]) |
| 13 | 2 |
| 14 | """ |
| 15 | self.vertices = vertices |
| 16 | self.graph = [[0] * vertices for _ in range(vertices)] |
| 17 | |
| 18 | def print_solution(self, distances_from_source: list[int]) -> None: |
| 19 | """ |
| 20 | >>> Graph(0).print_solution([]) # doctest: +NORMALIZE_WHITESPACE |
| 21 | Vertex Distance from Source |
| 22 | """ |
| 23 | print("Vertex \t Distance from Source") |
| 24 | for vertex in range(self.vertices): |
| 25 | print(vertex, "\t\t", distances_from_source[vertex]) |
| 26 | |
| 27 | def minimum_distance( |
| 28 | self, distances_from_source: list[int], visited: list[bool] |
| 29 | ) -> int: |
| 30 | """ |
| 31 | A utility function to find the vertex with minimum distance value, from the set |
| 32 | of vertices not yet included in shortest path tree. |
| 33 | |
| 34 | >>> Graph(3).minimum_distance([1, 2, 3], [False, False, True]) |
| 35 | 0 |
| 36 | """ |
| 37 | |
| 38 | # Initialize minimum distance for next node |
| 39 | minimum = 1e7 |
| 40 | min_index = 0 |
| 41 | |
| 42 | # Search not nearest vertex not in the shortest path tree |
| 43 | for vertex in range(self.vertices): |
| 44 | if distances_from_source[vertex] < minimum and visited[vertex] is False: |
| 45 | minimum = distances_from_source[vertex] |
| 46 | min_index = vertex |
| 47 | return min_index |
| 48 | |
| 49 | def dijkstra(self, source: int) -> None: |
| 50 | """ |
| 51 | Function that implements Dijkstra's single source shortest path algorithm for a |
| 52 | graph represented using adjacency matrix representation. |
| 53 | |
| 54 | >>> Graph(4).dijkstra(1) # doctest: +NORMALIZE_WHITESPACE |
| 55 | Vertex Distance from Source |
| 56 | 0 10000000 |
| 57 | 1 0 |
| 58 | 2 10000000 |
| 59 | 3 10000000 |
| 60 | """ |
| 61 | |