Skip to content

Instantly share code, notes, and snippets.

@abrahamy
Forked from econchick/gist:4666413
Last active March 7, 2018 08:47
Show Gist options
  • Save abrahamy/e46578cab7df82b4aa3f83258f0c6553 to your computer and use it in GitHub Desktop.
Save abrahamy/e46578cab7df82b4aa3f83258f0c6553 to your computer and use it in GitHub Desktop.
Python implementation of Dijkstra's Algorithm
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
self.distances = {}
def add_node(self, value):
self.nodes.add(value)
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.distances[(from_node, to_node)] = distance
def dijsktra(graph, initial):
visited = {initial: 0}
path = {}
nodes = set(graph.nodes)
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.remove(min_node)
current_weight = visited[min_node]
for edge in graph.edges[min_node]:
weight = current_weight + graph.distances[(min_node, edge)]
if edge not in visited or weight < visited[edge]:
visited[edge] = weight
path[edge] = min_node
return visited, path
@abrahamy
Copy link
Author

abrahamy commented Mar 7, 2018

Fixed typo on line 38 from the original fork, that is, graph.distance was changed to graph.distances

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