I made this implementation of dijkstra's algorithm of shortest paths with a priority dict based on heap. It has the following methods: smallest() - only returns the smallest key from the dict which has the smallest value. pop_smallest() returns the smallest key with the smallest value in the heap and also pops it from the heap dict. I tested the code on some tests on github and some tests are correct, some are not. I have seen many more implementations for this algo but i would want to make mine correct before i would see others which are better than mine.
I am a beginner, you may have the formed eye to identify what is wrong in my code. Kind regards, Edit: I don't know if i am allowed to post links to other websites but this website contains the tests i used: https://github.com/beaunus/stanford-algs/tree/master/testCases/course2/assignment2Dijkstra The context is that this implementation is part of an assignment for a coursera standford class about graphs. The assignment was to compute the distances to the 7'th node, 35'th node, etc). If some of these are wrong it is obvious something went wrong in the code. Just to be more clear , input_random_10_16 test outputs different answers. Not all the distances are correct.
- My implementation outputs : [878, 405, 785, 534, 909, 328, 708, 957, 830, 911]
- The correct answer is : [588, 405, 675, 521, 909, 328, 418, 957, 830, 839]
Some distances are correct, some are not.
EDIT: I finally remade a different implementation which passed all of the tests. This is the heap implementation. I also wanted to do the naive implementation which didn't use a heap. I searched online for different naive implementations and i found severall which output the same wrong results as this implementation. How is this possible? A good implementation also posted on github which worked for a lot of people when used on my graph outputed these wrong results.
def dijkstra(graph, s):
processed = set([s])
vertexes = set([])
distances = {}
ans = []
heap = priority_dict()
for i in graph:
vertexes.add(i)
distances[i] = 0
if i not in processed:
heap[i] = float('inf')
while processed != vertexes:
for i in processed:
neigh = graph[i]
for j in heap:
if j in neigh:
score = distances[i] + graph[i][j]
if score < heap[j]:
heap[j] = score
smallest_value = heap[heap.smallest()]
smallest_key = heap.pop_smallest()
processed.add(smallest_key)
distances[smallest_key] = smallest_value
for j in graph[smallest_key]:
if j in heap:
old_val = heap[j]
new_val = min(old_val, distances[smallest_key] + graph[smallest_key][j])
heap[j] = new_val
list_ = [7,37,59,82,99,115,133,165,188,197]
for i in list_:
ans.append(distances[i])
return ans
ain the calculation of the new distance? It doesn't seem to be defined anywhere