roads = { "S": [("G", 7), ("A", 2)], "A": [("G", 2)] } def search(by_cost): waiting = [(0, "S")] while waiting: if by_cost: cost, path = min(waiting, key=lambda item: item[0]) else: cost, path = min(waiting, key=lambda item: len(item[1])) waiting.remove((cost, path)) if path[-1] == "G": return path, cost for next_stop, price in roads[path[-1]]: waiting.append((cost + price, path + next_stop)) print(*search(False)) print(*search(True))