diff --git a/graphs/johnson_graph.py b/graphs/johnson_graph.py index 310650021..05ebc1116 100644 --- a/graphs/johnson_graph.py +++ b/graphs/johnson_graph.py @@ -2,85 +2,86 @@ from collections import deque import heapq import sys -#First implementation of johnson algorithm + +# First implementation of johnson algorithm class JohnsonGraph: def __init__(self): self.edges = [] self.graph = {} - - #add vertices for a graph + + # add vertices for a graph def add_vertices(self, u): self.graph[u] = [] - - #assign weights for each edges formed of the directed graph + + # assign weights for each edges formed of the directed graph def add_edge(self, u, v, w): self.edges.append((u, v, w)) - self.graph[u].append((v,w)) + self.graph[u].append((v, w)) - #perform a dijkstra algorithm on a directed graph + # perform a dijkstra algorithm on a directed graph def dijkstra(self, s): no_v = len(self.graph) - distances = {vertex: sys.maxsize-1 for vertex in self.graph} - pq = [(0,s)] - + distances = {vertex: sys.maxsize - 1 for vertex in self.graph} + pq = [(0, s)] + distances[s] = 0 while pq: weight, v = heapq.heappop(pq) - + if weight > distances[v]: continue - + for node, w in self.graph[v]: - if distances[v]+w < distances[node]: - distances[node] = distances[v]+w - heapq.heappush(pq, (distances[node], node)) + if distances[v] + w < distances[node]: + distances[node] = distances[v] + w + heapq.heappush(pq, (distances[node], node)) return distances - #carry out the bellman ford algorithm for a node and estimate its distance vector - def bellman_ford(self, s): + # carry out the bellman ford algorithm for a node and estimate its distance vector + def bellman_ford(self, s): no_v = len(self.graph) - distances = {vertex: sys.maxsize-1 for vertex in self.graph} + distances = {vertex: sys.maxsize - 1 for vertex in self.graph} distances[s] = 0 - + for u in self.graph: for u, v, w in self.edges: - if distances[u] != sys.maxsize-1 and distances[u]+w