forked from Ankitkundu21/Hacktoberfest-python-code-bunch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeighted_graph.py
More file actions
90 lines (56 loc) · 2.04 KB
/
Weighted_graph.py
File metadata and controls
90 lines (56 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from collections import defaultdict
#This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self,vertices):
self.V = vertices #No. of vertices
self.V_org = vertices
self.graph = defaultdict(list) # default dictionary to store graph
def addEdge(self,u,v,w):
if w == 1:
self.graph[u].append(v)
else:
self.graph[u].append(self.V)
self.graph[self.V].append(v)
self.V = self.V + 1
def printPath(self, parent, j):
Path_len = 1
if parent[j] == -1 and j < self.V_org : #Base Case : If j is source
print j,
return 0 # when parent[-1] then path length = 0
l = self.printPath(parent , parent[j])
Path_len = l + Path_len
if j < self.V_org :
print j,
return Path_len
''' This function mainly does BFS and prints the
shortest path from src to dest. It is assumed
that weight of every edge is 1'''
def findShortestPath(self,src, dest):
visited =[False]*(self.V)
parent =[-1]*(self.V)
# Create a queue for BFS
queue=[]
# Mark the source node as visited and enqueue it
queue.append(src)
visited[src] = True
while queue :
s = queue.pop(0)
if s == dest:
return self.printPath(parent, s)
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
parent[i] = s
g = Graph(4)
g.addEdge(0, 1, 2)
g.addEdge(0, 2, 2)
g.addEdge(1, 2, 1)
g.addEdge(1, 3, 1)
g.addEdge(2, 0, 1)
g.addEdge(2, 3, 2)
g.addEdge(3, 3, 2)
src = 0; dest = 3
print ("Shortest Path between %d and %d is " %(src, dest)),
l = g.findShortestPath(src, dest)
print ("\nShortest Distance between %d and %d is %d " %(src, dest, l)),