Dijkstra Algorithm is BFS with Priority Queue

in #programming4 years ago

Dijkstra Shortest Path Algorithm can be simply considered as the BFS (Breadth First Algorithm) with Priority Queue.

def dijkstra(s, e):
            if s == e:
                return 0
            q = [(0, s)]
            seen = set()
            d = { s: 0 }
            while q:
                c, v = heappop(q)
                if v in seen:
                    continue
                seen.add(v)
                for x, w in G[v]:
                    if c + w < d.get(x, inf):
                        d[x] = c + w
                        heappush(q, (c + w, x))
            return d.get(e, -1)

Dijkstra is a single source shortest path algorithm and thus it has a d array to store the shortest path from the source.

For more information, visit blog

Sort:  

Very educating. Thank you for this knowledge gained.

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.081
BTC 59794.17
ETH 1581.74
USDT 1.00
SBD 0.42