Skip to content

Commit 479f330

Browse files
Added the shortest path algorithm for directed acyclic graph.
1 parent 6a2b918 commit 479f330

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Python program to find single source shortest paths
2+
# for Directed Acyclic Graphs Complexity :OV(V+E)
3+
from collections import defaultdict
4+
5+
# Graph is represented using adjacency list. Every
6+
# node of adjacency list contains vertex number of
7+
# the vertex to which edge connects. It also contains
8+
# weight of the edge
9+
class Graph:
10+
def __init__(self,vertices):
11+
12+
self.V = vertices # No. of vertices
13+
14+
# dictionary containing adjacency List
15+
self.graph = defaultdict(list)
16+
17+
# function to add an edge to graph
18+
def addEdge(self,u,v,w):
19+
self.graph[u].append((v,w))
20+
21+
22+
# A recursive function used by shortestPath
23+
def topologicalSortUtil(self,v,visited,stack):
24+
25+
# Mark the current node as visited.
26+
visited[v] = True
27+
28+
# Recur for all the vertices adjacent to this vertex
29+
if v in self.graph.keys():
30+
for node,weight in self.graph[v]:
31+
if visited[node] == False:
32+
self.topologicalSortUtil(node,visited,stack)
33+
34+
# Push current vertex to stack which stores topological sort
35+
stack.append(v)
36+
37+
38+
''' The function to find shortest paths from given vertex.
39+
It uses recursive topologicalSortUtil() to get topological
40+
sorting of given graph.'''
41+
def shortestPath(self, s):
42+
43+
# Mark all the vertices as not visited
44+
visited = [False]*self.V
45+
stack =[]
46+
47+
# Call the recursive helper function to store Topological
48+
# Sort starting from source vertice
49+
for i in range(self.V):
50+
if visited[i] == False:
51+
self.topologicalSortUtil(s,visited,stack)
52+
53+
# Initialize distances to all vertices as infinite and
54+
# distance to source as 0
55+
dist = [float("Inf")] * (self.V)
56+
dist[s] = 0
57+
58+
# Process vertices in topological order
59+
while stack:
60+
61+
# Get the next vertex from topological order
62+
i = stack.pop()
63+
64+
# Update distances of all adjacent vertices
65+
for node,weight in self.graph[i]:
66+
if dist[node] > dist[i] + weight:
67+
dist[node] = dist[i] + weight
68+
69+
# Print the calculated shortest distances
70+
for i in range(self.V):
71+
print ("%d" %dist[i]) if dist[i] != float("Inf") else "Inf" ,
72+
73+
74+
g = Graph(6)
75+
g.addEdge(0, 1, 5)
76+
g.addEdge(0, 2, 3)
77+
g.addEdge(1, 3, 6)
78+
g.addEdge(1, 2, 2)
79+
g.addEdge(2, 4, 4)
80+
g.addEdge(2, 5, 2)
81+
g.addEdge(2, 3, 7)
82+
g.addEdge(3, 4, -1)
83+
g.addEdge(4, 5, -2)
84+
85+
# source = 1
86+
s = 1
87+
88+
print ("Following are shortest distances from source %d " % s)
89+
g.shortestPath(s)

0 commit comments

Comments
 (0)