Skip to content

Instantly share code, notes, and snippets.

@sugayaa
Last active November 28, 2018 14:52
Show Gist options
  • Save sugayaa/25bb31f943249b0522a1622b17053367 to your computer and use it in GitHub Desktop.
Save sugayaa/25bb31f943249b0522a1622b17053367 to your computer and use it in GitHub Desktop.
#dijkstra single source using networkx in python3
def dijkstraSingleSource(source):
pq = []
dist = [m.inf] * TAM
vis = [False] * TAM
pred = [-1] * TAM
heapq.heappush(pq, (0 ,source))
dist[source] = 0
#laço principal
while len(pq) != 0:
#recebe indice do nó atual que olharemos (current node)
curr_node = heapq.heappop(pq)[1]
#caso ñ foi visitado, prossegue
if not vis[curr_node]:
#marca como visitado
vis[curr_node] = True
#percorrendo lista de adjacencia do nó atual
for neighbors in G.adj[curr_node]:
#recebe vértice a quem o atual se liga (next node)
next_node = neighbors
#recebe peso da aresta que liga curr_node -w-> next_node
w = G.adj[curr_node][next_node]['weight']
#relax
if dist[next_node] > dist[curr_node] + w:
pred[next_node] = curr_node
dist[next_node] = dist[curr_node] + w
heapq.heappush(pq, (dist[next_node], next_node))
return dist, pred
@sugayaa
Copy link
Author

sugayaa commented Nov 28, 2018

import networkx
import heapq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment