Skip to content

Commit ab190be

Browse files
Warshall Algorithm
1 parent e56a817 commit ab190be

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
'''
2+
A program for warshall algorithm.It is a shortest path algorithm which is used to find the
3+
distance from source node,which is the first node,to all the other nodes.
4+
If there is no direct distance between two vertices then it is considered as -1
5+
'''
6+
7+
8+
def warshall(g,ver):
9+
dist = list(map(lambda i: list(map(lambda j: j, i)), g))
10+
for i in range(0,ver):
11+
for j in range(0,ver):
12+
dist[i][j] = g[i][j]
13+
#Finding the shortest distance if found
14+
for k in range(0,ver):
15+
for i in range(0,ver):
16+
for j in range(0,ver):
17+
if dist[i][k] + dist[k][j] < dist[i][j] and dist[i][k]!=-1 and dist[k][j]!=-1:
18+
dist[i][j] = dist[i][k] + dist[k][j]
19+
#Prnting the complete short distance matrix
20+
print("The distance matrix is\n")
21+
for i in range(0,ver):
22+
for j in range(0,ver):
23+
if dist[i][j]>=0:
24+
print(dist[i][j],end=" ")
25+
else:
26+
print(-1,end=" ")
27+
print("\n")
28+
#Driver's code
29+
def main():
30+
print("Enter number of vertices\n")
31+
ver=int(input())
32+
graph=[]
33+
#Creating the graph
34+
print("Enter the graph\n")
35+
for i in range(ver):
36+
a =[]
37+
for j in range(ver):
38+
a.append(int(input()))
39+
graph.append(a)
40+
warshall(graph,ver)
41+
if __name__=="__main__":
42+
main()
43+
44+
45+
46+
'''
47+
Time Complexity:O(ver^3)
48+
Space Complexity:O(ver^2)
49+
Input/Output:
50+
Enter number of vertices
51+
4
52+
Enter the graph
53+
0
54+
8
55+
-1
56+
1
57+
-1
58+
0
59+
1
60+
-1
61+
4
62+
-1
63+
0
64+
-1
65+
-1
66+
2
67+
9
68+
0
69+
The distance matrix is
70+
0 3 -1 1
71+
-1 0 1 -1
72+
4 -1 0 -1
73+
-1 2 3 0
74+
'''

0 commit comments

Comments
 (0)