""" python algorithm for single source shortest path """ from collections import defaultdict
classGraph: ## find vertex with minium dist value, ## from the set of vertices still in the queue defmin_distance(self, dist, queue): minimum = float('inf') min_index = -1
## from dist array, pick one which has min value and still in queue for i in range(len(queue)): if dist[i] < minimum and i in queue: minimum = dist[i] min_index = i return min_index
## print shortest path from source to j using parent array defprint_path(self, parent, j): ## base: if j is source if parent[j] == -1: print(j) return self.print_path(parent, parent[j])
## print constructed distince array defprint_solution(self, dist, parent): src = 0 print('vertex \t \tdistance from source \tpath') for i in range(1, len(dist)): print('\n%d--> %d \t \t%d \t\t\t\t\t' %(src, i, dist[i])) self.print_path(parent, i)
## dijstra using adjacent matrix defdijkstra(self, graph, src): row, col = len(graph), len(graph[0])
## init all distances to infinite, parent store shortest path tree dist = [float['inf']] * row parent = [-1] * row
## src vertex would be 0 dist[src] = 0 queue = [] for i in range(row): queue.append(i)
while queue: ## pick minimus dist vertex from set of vertices still in queue u = self.min_distance(dist, queue) queue.remove(u)
## update dist value and parent index of the adjacent vertices of the picked vertex ## consider only those vertices which are still in queue for i in range(col): ## update dist[i] only if it is in the queue, and there is ## an edge from u to i, and the total weight of path from src to i througth u ## is smaller than current dist[i] if graph[u][i] and i in queue: if dist[u] + graph[u][i] < dist[i]: dist[i] = dist[u] + graph[u][i] parent[i] = u