Created
September 15, 2015 09:59
-
-
Save rishi93/39d9f8a2bfc6866b49c9 to your computer and use it in GitHub Desktop.
Dijkstra's Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class vertex(): | |
def __init__(self,name): | |
self.name = name | |
self.neighbours = [] | |
def connected_to(self,vertex,distance): | |
self.neighbours.append((vertex,distance)) | |
class graph(): | |
def __init__(self): | |
self.vertices = [] | |
def add_vertex(self,vertex): | |
self.vertices.append(vertex) | |
def minimum(arr,mask): | |
for i in range(0,len(arr),1): | |
if mask[i] is False: | |
minimum,index = arr[i],i | |
break | |
for i in range(0,len(arr),1): | |
if mask[i] is False and arr[i] < minimum: | |
minimum,index = arr[i],i | |
return minimum,index | |
def allvisited(arr): | |
for elem in arr: | |
if elem is False: | |
return False | |
return True | |
graph1 = graph() | |
a = vertex(0) | |
b = vertex(1) | |
c = vertex(2) | |
d = vertex(3) | |
e = vertex(4) | |
a.connected_to(b,4) | |
a.connected_to(c,1) | |
b.connected_to(e,3) | |
c.connected_to(b,2) | |
c.connected_to(d,2) | |
d.connected_to(e,3) | |
graph1.add_vertex(a) | |
graph1.add_vertex(b) | |
graph1.add_vertex(c) | |
graph1.add_vertex(d) | |
graph1.add_vertex(e) | |
distances = [100 for _ in range(0,len(graph1.vertices))] | |
distances[0] = 0 | |
print distances | |
visited = [False for _ in range(0,len(graph1.vertices))] | |
print visited | |
while allvisited(visited) is False: | |
curr_dist,curr_vertex = minimum(distances,visited) | |
print curr_vertex | |
for nearby in graph1.vertices[curr_vertex].neighbours: | |
neighbour,neighbour_distance = nearby[0].name,nearby[1] | |
if curr_dist + neighbour_distance < distances[neighbour]: | |
distances[neighbour] = curr_dist + neighbour_distance | |
visited[curr_vertex] = True | |
print distances | |
print visited |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment