I'm trying to implement Dijkstra's algorithm in Python and something doesn't work. I think there is a problem somewhere and I cannot find it. Here's my code:
def Dijkstra(self, start, end, visited=[], distances = {}, predecessors = {}):
allV = self.__repo.read_first_line()
verteces = allV[0]
if start == end:
# We build the shortest path and display it
path=[]
pred=end
while pred != None:
path.append(pred)
pred=predecessors.get(pred,None)
path.reverse()
print('Shortest path: '+str(path)+ " - " + "Cost = "+str(distances[start]))
else :
if not visited:
distances[start]=0
# visit the neighbors
neighbours = self.__repo.get_neighbours(start)
for neighbor in neighbours :
if neighbor not in visited:
new_distance = distances[start] + self.get_cost(start, neighbor)
if new_distance < distances.get(neighbor,float('inf')):
distances[neighbor] = new_distance
predecessors[neighbor] = start
# mark as visited
visited.append(start)
# now that all neighbors have been visited: recurse
# select the non visited node with lowest distance 'x'
# run Dijskstra with start='x'
unvisited={}
for k in range(1,int(verteces) + 1):
if k not in visited:
unvisited[k] = distances.get(k,float('inf'))
x=min(unvisited, key=unvisited.get)
self.Dijkstra(x,end,visited,distances,predecessors)