Skip to content

Commit 2f8929a

Browse files
authored
Create floyd_warshall.py
1 parent 50b02f8 commit 2f8929a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

dynamic-programming/floyd_warshall.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Copyright (c) June 02, 2017 CareerMonk Publications and others.
2+
3+
# Creation Date : 2017-06-02 06:15:46
4+
# Last modification : 2017-06-02
5+
# Modified by : Narasimha Karumanchi
6+
# Book Title : Algorithm Design Techniques
7+
# Warranty : This software is provided "as is" without any
8+
# warranty; without even the implied warranty of
9+
# merchantability or fitness for a particular purpose.
10+
11+
def adj(graph):
12+
vertices = graph.keys()
13+
14+
D = {}
15+
for i in vertices:
16+
D[i] = {}
17+
for j in vertices:
18+
try:
19+
D[i][j] = graph[i][j]
20+
except KeyError:
21+
# the distance from a node to itself is 0
22+
if i == j:
23+
D[i][j] = 0
24+
# the distance from a node to an unconnected node is infinity
25+
else:
26+
D[i][j] = float('inf')
27+
return D
28+
29+
def floyd_warshall(graph):
30+
vertices = graph.keys()
31+
32+
d = dict(graph) # copy graph
33+
for k in vertices:
34+
for i in vertices:
35+
for j in vertices:
36+
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
37+
return d
38+
39+
40+
if __name__ == "__main__":
41+
graph = {'c': {'a':5, 'b':2, 'd':1, 'h':2},
42+
'a': {'b':3, 'c':5, 'e':8, 'f':1},
43+
'b': {'a':3, 'c':2, 'g':1},
44+
'd': {'c':1, 'e':4},
45+
'e': {'a':8, 'd':4, 'f':6, 'h':1},
46+
'f': {'a':1, 'e':6, 'g':5},
47+
'g': {'b':1, 'f':5, 'h':1},
48+
'h': {'c':2, 'e':1, 'g':1}}
49+
matrix=adj(graph)
50+
print matrix
51+
print floyd_warshall(matrix)
52+

0 commit comments

Comments
 (0)