Question Need help with a problem in the implementation of Dijkstra's algorithm.

Please provide comments and solutions that are helpful to the author of this topic.

quentisa

Level 1
Thread author
Jan 6, 2023
11
I'm presently working on implementing Dijkstra's method for a graph traversal problem, however I'm having trouble figuring out an error. The method succeeds, but the shortest path it generates is inaccurate.
Here's a piece of code that computes the shortest distances:
Code:
distances = [float('inf')] * num_nodes
distances[source] = 0
visited = [False] * num_nodes

while True:
    min_distance = float('inf')
    min_node = -1

    for node in range(num_nodes):
        if not visited[node] and distances[node] < min_distance:
            min_distance = distances[node]
            min_node = node

    if min_node == -1:
        break

    visited[min_node] = True

    for neighbor in graph[min_node]:
        new_distance = distances[min_node] + graph[min_node][neighbor]
        if new_distance < distances[neighbor]:
            distances[neighbor] = new_distance
I went through the code and double-checked my graph representation to ensure that the edge weights are not negative, and I read the scaler article for Dijkstra's algorithm to get a check. Despite the fact that the method ends, the distances calculated are incorrect for some nodes.

I believe there is a problem with the termination condition or the way I label nodes as visited. Could the loop condition or the method I update the visited list have a logical flaw? I can't figure out what's causing the wrong distances.

I would highly appreciate your aid if you have any thoughts or recommendations on how to address this mistake and assure the right shortest path lengths. Thank you ahead of time!"
 
  • Like
Reactions: simmerskool

simmerskool

Level 37
Verified
Top Poster
Well-known
Apr 16, 2017
2,607
wondering if you've tried openai chatgpt since I've heard that it is good at checking code
 

About us

  • MalwareTips is a community-driven platform providing the latest information and resources on malware and cyber threats. Our team of experienced professionals and passionate volunteers work to keep the internet safe and secure. We provide accurate, up-to-date information and strive to build a strong and supportive community dedicated to cybersecurity.

User Menu

Follow us

Follow us on Facebook or Twitter to know first about the latest cybersecurity incidents and malware threats.

Top