# note: I added Anaheim to the sample graph here. The solution should work # appropriately with either graph. sample_graph = { 'Santa Ana': { 'Los Angeles': 5, 'Anaheim': 3, 'Palm Springs': 50 }, 'Anaheim': { 'Los Angeles': 2, 'Santa Ana': 3 }, 'Los Angeles': { 'Anaheim': 2, 'San Francisco': 25, 'Santa Ana': 5 }, 'Palm Springs': { 'San Francisco': 30, 'Santa Ana': 50 }, 'San Francisco': { 'Los Angeles': 25, 'Palm Springs': 30 } } def possible_paths(graph: dict[str, dict[str, int]], start: str, end: str): # (path, total distance represented by path) queue = [([start], 0)] valid_paths = [] # appending to queue: # append the new vertex to the path, add the distance to the total distance # do not append to queue if in visited while queue: path, distance = queue.pop(0) if path[-1] == end: valid_paths.append((path, distance)) else: for vertex, weight in graph[path[-1]].items(): # question: what can we do to improve time efficiency here? if vertex not in path: new_path = path.copy() new_path.append(vertex) queue.append((new_path, distance + weight)) return valid_paths print(possible_paths(sample_graph, 'Santa Ana', 'San Francisco'))