-
-
Save hsavit1/95d1a338ae54d4477ac0 to your computer and use it in GitHub Desktop.
Modified Python implementation of Dijkstra's Algorithm (https://gist.github.com/econchick/4666413)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Graph: | |
| def __init__(self): | |
| self.nodes = set() | |
| self.edges = defaultdict(list) | |
| self.distances = {} | |
| return self | |
| def add_node(self, value): | |
| self.nodes.add(value) | |
| return self | |
| 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 | |
| return self | |
| 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]: | |
| try: | |
| weight = current_weight + graph.distance[(min_node, edge)] | |
| except: | |
| continue | |
| if edge not in visited or weight < visited[edge]: | |
| visited[edge] = weight | |
| path[edge] = min_node | |
| return visited, path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment