Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import defaultdict, deque
- """
- ~/v/H/p/s/py ❯❯❯ python3 dijkstra.py
- {'G', 'B', 'E', 'A', 'D', 'F', 'C'}
- {'A': 0}
- nodes={'G', 'B', 'E', 'D', 'F', 'C'} visited={'B': 10, 'C': 20, 'A': 0} min_node=A
- nodes={'G', 'E', 'D', 'F', 'C'} visited={'D': 25, 'E': 60, 'B': 10, 'C': 20, 'A': 0} min_node=B
- nodes={'G', 'E', 'D', 'F'} visited={'D': 25, 'E': 60, 'B': 10, 'C': 20, 'A': 0} min_node=C
- nodes={'G', 'E', 'F'} visited={'D': 25, 'E': 55, 'B': 10, 'C': 20, 'A': 0} min_node=D
- nodes={'G', 'F'} visited={'B': 10, 'E': 55, 'A': 0, 'D': 25, 'F': 60, 'C': 20} min_node=E
- nodes={'G'} visited={'B': 10, 'E': 55, 'A': 0, 'D': 25, 'G': 62, 'F': 60, 'C': 20} min_node=F
- nodes=set() visited={'B': 10, 'E': 55, 'A': 0, 'D': 25, 'G': 62, 'F': 60, 'C': 20} min_node=G
- (25, ['A', 'B', 'D'])
- """
- class Graph(object):
- 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 dijkstra(graph, initial):
- visited = {initial: 0}
- path = {}
- nodes = set(graph.nodes)
- print(nodes)
- print(visited)
- 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]
- # enumerate all adjacent nodes of min_node
- for node in graph.edges[min_node]:
- try:
- weight = current_weight + graph.distances[(min_node, node)]
- except:
- continue
- if node not in visited or weight < visited[node]:
- visited[node] = weight
- path[node] = min_node
- print("nodes=%s visited=%s min_node=%s" % (nodes, visited, min_node))
- return visited, path
- def shortest_path(graph, origin, destination):
- visited, paths = dijkstra(graph, origin)
- full_path = deque()
- _destination = paths[destination]
- while _destination != origin:
- full_path.appendleft(_destination)
- _destination = paths[_destination]
- full_path.appendleft(origin)
- full_path.append(destination)
- return visited[destination], list(full_path)
- if __name__ == '__main__':
- graph = Graph()
- for node in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
- graph.add_node(node)
- graph.add_edge('A', 'B', 10)
- graph.add_edge('A', 'C', 20)
- graph.add_edge('B', 'D', 15)
- graph.add_edge('C', 'D', 30)
- graph.add_edge('B', 'E', 50)
- graph.add_edge('D', 'E', 30)
- graph.add_edge('E', 'F', 5)
- graph.add_edge('F', 'G', 2)
- print(shortest_path(graph, 'A', 'D')) # output: (25, ['A', 'B', 'D'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement