CodexBloom - Programming Q&A Platform

Unexpected Infinite Loop in Dijkstra's Algorithm Implementation with Priority Queue in Python

👀 Views: 80 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
python algorithms dijkstra data-structures Python

I've been working on this all day and I'm prototyping a solution and I tried several approaches but none seem to work. I'm currently implementing Dijkstra's algorithm to find the shortest path in a weighted graph using Python and the `heapq` library for the priority queue. However, I'm working with an infinite loop when processing nodes, which I need to seem to resolve. My graph is represented as an adjacency list, and I have a simple implementation as follows: ```python import heapq def dijkstra(graph, start): queue = [(0, start)] # (distance, vertex) distances = {vertex: float('infinity') for vertex in graph} distances[start] = 0 visited = set() while queue: current_distance, current_vertex = heapq.heappop(queue) if current_vertex in visited: continue visited.add(current_vertex) for neighbor, weight in graph[current_vertex].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(queue, (distance, neighbor)) return distances ``` I'm passing in a graph that looks like this: ```python graph = { 'A': {'B': 1, 'C': 4}, 'B': {'A': 1, 'C': 2, 'D': 5}, 'C': {'A': 4, 'B': 2, 'D': 1}, 'D': {'B': 5, 'C': 1} } ``` When I run the function as `dijkstra(graph, 'A')`, I expect to get the shortest distances from vertex 'A'. However, I find that the loop continues indefinitely without ever finishing, and I don't get any output or errors. I've tried adding print statements to debug the current vertex and queue state, but it seems to loop through the same vertices repeatedly. Could I be missing something in my distance comparison or queue management? Any guidance would be greatly appreciated! This is part of a larger API I'm building. What am I doing wrong? I'm coming from a different tech stack and learning Python. What would be the recommended way to handle this? I'm working on a web app that needs to handle this. I'd be grateful for any help. I'm developing on Ubuntu 22.04 with Python.