dijkstra's algorithm python code using priority queue
- User
dijkstra's algorithm python code using priority queue
- Assistant
Here is the Python code for Dijkstra's algorithm using a priority queue:
import heapq def dijkstra(graph, start): # Initialize distances dictionary with infinity for all nodes except start node distances = {node: float('inf') for node in graph} distances[start] = 0 # Initialize priority queue with start node priority_queue = [(0, start)] while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) # Skip if current distance is greater than the recorded distance if current_distance > distances[current_node]: continue # Explore adjacent nodes and update distances if shorter path is found for neighbor, weight in graph[current_node].items(): distance = current_distance + weight if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(priority_queue, (distance, neighbor)) return distances # Example usage graph = { 'A': {'B': 2, 'C': 5}, 'B': {'A': 2, 'C': 8, 'D': 7}, 'C': {'A': 5, 'B': 8, 'D': 1}, 'D': {'B': 7, 'C': 1} } start_node = 'A' distances = dijkstra(graph, start_node) print(distances) - User
Python code for prims algorithm
- Assistant
Here is the Python code for Prim's algorithm to find the minimum spanning tree of a weighted graph:
import heapq def prims(graph, start): min_spanning_tree = {} visited = set() # Initialize priority queue with start node priority_queue = [(0, start)] while priority_queue: current_weight, current_node = heapq.heappop(priority_queue) # Skip if current node has already been visited if current_node in visited: continue visited.add(current_node) if current_node in min_spanning_tree: # If current node is already in the minimum spanning tree, skip continue if current_node != start: # Add current node and its parent to the minimum spanning tree parent_node = min_spanning_tree[current_node][1] min_spanning_tree[current_node] = (current_weight, parent_node) # Explore adjacent nodes and add to priority queue for neighbor, weight in graph[current_node].items(): heapq.heappush(priority_queue, (weight, neighbor)) return min_spanning_tree # Example usage graph = { 'A': {'B': 2, 'C': 5, 'D': 1}, 'B': {'A': 2, 'C': 3, 'E': 1}, 'C': {'A': 5, 'B': 3, 'D': 2, 'E': 4}, 'D': {'A': 1, 'C': 2, 'E': 6}, 'E': {'B': 1, 'C': 4, 'D': 6} } start_node = 'A' minimum_spanning_tree = prims(graph, start_node) print(minimum_spanning_tree)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.