Pemilihan Jalur Tercepat Menggunakan Algoritma Dijkstra
Pemilihan Jalur Tercepat Menggunakan Algoritma Dijkstra
PENGALIASAN
Programming on python
import sys
def
shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
"""Find the shortest path between start and end nodes in a graph"""
# we've found our end node, now find the path to it, and return
if start==end:
path=[]
while end != None:
path.append(end)
end=predecessors.get(end,None)
return distances[start], path[::-1]
# detect if it's the first time through, set current distance to zero
if not visited: distances[start]=0
# process neighbors as per algorithm, keep track of predecessors
for neighbor in graph[start]:
if neighbor not in visited:
neighbordist = distances.get(neighbor,sys.maxint)
tentativedist = distances[start] + graph[start][neighbor]
if tentativedist < neighbordist:
distances[neighbor] = tentativedist
predecessors[neighbor]=start
# neighbors processed, now mark the current node as visited
visited.append(start)
# finds the closest unvisited node to the start
unvisiteds = dict((k, distances.get(k,sys.maxint)) for k in graph if k not
in visited)
closestnode = min(unvisiteds, key=unvisiteds.get)
# now we can take the closest node and recurse, making it current
return
shortestpath(graph,closestnode,end,visited,distances,predecessors)
if __name__ == "__main__":
graph = {'a': {'b': 8.84, 'j': 11.61, 'o': 4.32},
'b': {'c': 6.65, 'd': 5.49},
'c': {'d': 5.49},
'd': {'e': 2.67},
'e': {'h': 4.16, 'f': 2.51},
'f': {'g': 8.37},
'g': {'h': 8.37, 'f': 8.37, 'm': 14.81},
'h': {'e': 4.16, 'k': 0.83, 'm': 7.24, 'g': 8.37},
'i': {'j': 2.4, 'k': 6.62},
'j': {'i': 2.4, 'l': 2.24, 'n': 1.84, 'a': 11.61},
an