Skip to content

Commit 1da2bfd

Browse files
committed
graph algorithms
1 parent 2ec537c commit 1da2bfd

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import sys
2+
def to_be_visited():
3+
global visited_and_distance
4+
v = -10
5+
for index in range(number_of_vertices):
6+
if visited_and_distance[index][0] == 0 \
7+
and (v < 0 or visited_and_distance[index][1] <= \
8+
visited_and_distance[v][1]):
9+
v = index
10+
return v
11+
vertices = [[0, 1, 1, 0],
12+
[0, 0, 1, 0],
13+
[0, 0, 0, 1],
14+
[0, 0, 0, 0]]
15+
edges = [[0, 3, 4, 0],
16+
[0, 0, 0.5, 0],
17+
[0, 0, 0, 1],
18+
[0, 0, 0, 0]]
19+
20+
number_of_vertices = len(vertices[0])
21+
visited_and_distance = [[0, 0]]
22+
for i in range(number_of_vertices-1):
23+
visited_and_distance.append([0, sys.maxsize])
24+
25+
for vertex in range(number_of_vertices):
26+
to_visit = to_be_visited()
27+
for neighbor_index in range(number_of_vertices):
28+
if vertices[to_visit][neighbor_index] == 1 and \
29+
visited_and_distance[neighbor_index][0] == 0:
30+
new_distance = visited_and_distance[to_visit][1] \
31+
+ edges[to_visit][neighbor_index]
32+
if visited_and_distance[neighbor_index][1] > new_distance:
33+
visited_and_distance[neighbor_index][1] = new_distance
34+
visited_and_distance[to_visit][0] = 1
35+
36+
i = 0
37+
38+
for distance in visited_and_distance:
39+
print("The shortest distance of ",chr(ord('a') + i),\
40+
" from the source vertex a is:",distance[1])
41+
i = i + 1
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
nV = 4
3+
4+
INF = 999
5+
6+
def floyd_warshall(G):
7+
distance = list(map(lambda i: list(map(lambda j: j, i)), G))
8+
for k in range(nV):
9+
for i in range(nV):
10+
for j in range(nV):
11+
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
12+
print_solution(distance)
13+
14+
def print_solution(distance):
15+
for i in range(nV):
16+
for j in range(nV):
17+
if(distance[i][j] == INF):
18+
print("INF", end=" ")
19+
else:
20+
print(distance[i][j], end=" ")
21+
print(" ")
22+
23+
24+
G = [[0, 3, INF, 5],
25+
[2, 0, INF, 4],
26+
[INF, 1, 0, INF],
27+
[INF, INF, 2, 0]]
28+
floyd_warshall(G)
29+
Floyd Warshall Algorithm Complexity
30+
Time Complexity
31+
There are three lo

0 commit comments

Comments
 (0)