pseudocode dijkstragraph g start vertex s destination vertex d all nodes initially unexplored 1 let h min heap data structure initialized with 0 and s here 0 indicates the distance from start vertex s 2 while h is nonempty 3 remove the first node and cost of h call it u and cost 4 if u has been previously explored 5 go to the while loop line 2 once a node is explored there is no need to make it again 6 mark u as explored 7 if u is d 8 return cost total cost from start to destination vertex 9 for each edgeu v ccost of edgeu v for v in graphu 10 if v explored 11 go to next v in line 9 12 totalcost cost c 13 add totalcost v to h you can think at cost as a distance where dijkstra finds the shortest distance between vertices s and v in a graph g the use of a min heap as h guarantees that if a vertex has already been explored there will be no other path with shortest distance that happens because heapq heappop will always return the next vertex with the shortest distance considering that the heap stores not only the distance between previous vertex and current vertex but the entire distance between each vertex that makes up the path from start vertex to target vertex return the cost of the shortest path between vertices start and end dijkstrag e c 6 dijkstrag2 e f 3 dijkstrag3 e f 3 g2 b c 1 c d 1 d f 1 e b 1 f 3 f r layout of g3 e 1 b 1 c 1 d 1 f 2 g 1 return the cost of the shortest path between vertices start and end dijkstra g e c 6 dijkstra g2 e f 3 dijkstra g3 e f 3 cost from start node end node layout of g2 e 1 b 1 c 1 d 1 f 3 layout of g3 e 1 b 1 c 1 d 1 f 2 g 1 e 3 f 3 c 6 e 3 f 3 e 2 g 1 f 3
import heapq


def dijkstra(graph, start, end):
    

    heap = [(0, start)]  
    visited = set()
    while heap:
        (cost, u) = heapq.heappop(heap)
        if u in visited:
            continue
        visited.add(u)
        if u == end:
            return cost
        for v, c in graph[u]:
            if v in visited:
                continue
            next_item = cost + c
            heapq.heappush(heap, (next_item, v))
    return -1


G = {
    "A": [["B", 2], ["C", 5]],
    "B": [["A", 2], ["D", 3], ["E", 1], ["F", 1]],
    "C": [["A", 5], ["F", 3]],
    "D": [["B", 3]],
    "E": [["B", 4], ["F", 3]],
    "F": [["C", 3], ["E", 3]],
}

r
G2 = {
    "B": [["C", 1]],
    "C": [["D", 1]],
    "D": [["F", 1]],
    "E": [["B", 1], ["F", 3]],
    "F": [],
}

r
G3 = {
    "B": [["C", 1]],
    "C": [["D", 1]],
    "D": [["F", 1]],
    "E": [["B", 1], ["G", 2]],
    "F": [],
    "G": [["F", 1]],
}

short_distance = dijkstra(G, "E", "C")
print(short_distance)  

short_distance = dijkstra(G2, "E", "F")
print(short_distance)  

short_distance = dijkstra(G3, "E", "F")
print(short_distance)  

if __name__ == "__main__":
    import doctest

    doctest.testmod()