Skip to content
Snippets Groups Projects
Commit 2f9feac5 authored by cs3555's avatar cs3555
Browse files

q5

parent a5291221
Branches
No related tags found
No related merge requests found
#!/usr/bin/env python3
def dijkstra(matrix, height, start):
distances = matrix[start-1]
visited = [start]
vertices = []
for i in range(height):
vertices.append(i)
while vertices:
min = float("Inf")
idx = findmin(height, distances, vertices)
vertices.remove(idx)
for i in range(height):
if i in vertices and matrix[0][i] and distances[i] > 0:
if distances[i-1] + matrix[0][i-1] < matrix[0][i]:
distances[idx] = distances[i-1] + matrix[0][i]
print("Shortest distances from vertex %d to other vertices:\n" % start)
for i in range(height):
print("(%d,%d): %d" % (start, i+1, distances[i]))
def findmin(height, distances, vertices):
min = float("Inf")
idx = 0
for i in range(height):
if i in vertices and distances[i] < min:
min = distances[i]
idx = i
return idx
if __name__=="__main__":
#adjacency matric from test 2, problem 6, as a 2D array
matrix = [[0, 4, 1, 5, 8, 10],
[4, 0, 2, 0, 0, 0],
[1, 2, 0, 0, 0, 0],
[5, 0, 0, 0, 2, 1],
[8, 0, 0, 2, 0, 1],
[10, 0, 0, 0, 1, 0]]
print("Input Matrix:\n")
print("0 4 1 5 8 10\n4 0 2 0 0 0\n1 2 0 0 0 0\n5 0 0 0 2 0\n8 0 0 2 0 1\n10 0 0 0 1 0\n")
#gets height and width, without just assuming 6
height = len(matrix)
start = 1
dijkstra(matrix, height, start)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment