Complete the code to add an edge between two nodes in a graph represented as an adjacency list.
graph = {}
def add_edge(u, v):
if u not in graph:
graph[u] = []
graph[u].append([1])We add the node v to the adjacency list of u to represent an edge from u to v.
Complete the code to initialize the distance dictionary with infinity for all nodes in the graph.
distance = {node: [1] for node in graph}We use float('inf') to represent an initially infinite distance to all nodes before running the shortest path algorithm.
Fix the error in the code that updates the distance to a neighbor node during shortest path calculation.
if distance[current] + weight < distance[[1]]: distance[neighbor] = distance[current] + weight
The distance to the neighbor node is updated if a shorter path is found through the current node.
Fill both blanks to complete the BFS traversal code that finds shortest paths in an unweighted graph.
from collections import deque queue = deque([start]) distance = {start: 0} while queue: current = queue.popleft() for neighbor in graph[current]: if neighbor not in distance: distance[neighbor] = distance[current] [1] 1 queue.[2](neighbor)
We add 1 to the current distance to get the neighbor's distance and append the neighbor to the queue for BFS.
Fill all three blanks to complete the Dijkstra's algorithm step that updates distances and adds nodes to the priority queue.
import heapq heap = [] heapq.heappush(heap, (0, start)) while heap: current_distance, current_node = heapq.heappop(heap) if current_distance > distance[current_node]: continue for neighbor, weight in graph[current_node]: distance_through_current = current_distance [1] weight if distance_through_current < distance[[2]]: distance[neighbor] = distance_through_current heapq.[3](heap, (distance_through_current, neighbor))
We add the edge weight to the current distance, compare with the neighbor's distance, update if smaller, and push the neighbor with updated distance into the heap.
