I have an an algorithm that iterates via BFS the whole graph, and it will update the score to find the min values to all nodes. And I believe the runtime complexity of this is O(V+E), which I believe is better than Dijkstra. Now obviously I'm not naive enough to actually think this algorithm is correct. However, I'm curious in which case, this would not find the optimal min path. here is the code I have
from queue import Queue
ad_list = {
'A': {'B': 1, 'D': 3},
'B': {'A': 1, 'D': 1, 'C': 5},
'D': {'A': 3, 'B': 1, 'C': 3},
'C': {'B': 5, 'D': 3}
}
min_weights = {
'A': 0,
'B': float('inf'),
'C': float('inf'),
'D': float('inf'),
}
def fake_dijkstra(ad_list):
queue = Queue()
queue.put('A')
visited = {}
global min_weights
while not queue.empty():
key = queue.get()
# update score
children = ad_list[key]
for child_key, value in children.items():
if min_weights[child_key] > min_weights[key] + value:
min_weights[child_key] = min_weights[key] + value
if key in visited:
continue
visited[key] = True
children = ad_list[key]
for child_key, value in children.items():
queue.put(child_key)
fake_dijkstra(ad_list)
print(min_weights)
# for this case, it correctly finds the min weight to all nodes
{'A': 0, 'B': 1, 'C': 5, 'D': 2}
Any feedback would be highly appreciated. I love algorithms :).