Joker666
10/9/2015 - 4:33 PM

Shortest Path

Shortest Path

# MD Ahad Hasan
# ID: 1211028042
# Assignment 1

import itertools
from pythonds.graphs import PriorityQueue, Graph


def readLines(fName):
    f = open(fName, 'r')
    lines = [l.rstrip('\n') for l in itertools.takewhile(lambda x: x != 'END OF INPUT\n', f)]
    f.close()
    return lines


def dijkstra(aGraph, start, target):
    PQ = PriorityQueue()
    start.setDistance(0)  # Set the start distance to 0
    PQ.buildHeap([(v.getDistance(), v) for v in aGraph])  # Build the min heap queue

    while not PQ.isEmpty():
        currentVertex = PQ.delMin()  # Take the first one which is minimum
        if currentVertex == target:
            return

        for nextVertex in currentVertex.getConnections():  # For all the adjacent vertices
            newDistance = currentVertex.getDistance() + \
                          currentVertex.getWeight(
                              nextVertex)  # Current vertex's weight and the cost to reach the next vertex
            if newDistance < nextVertex.getDistance():  # Compare with next vertex's weight
                nextVertex.setDistance(newDistance)  # Set the new distance
                nextVertex.setPred(currentVertex)  # Specify the predecessor
                PQ.decreaseKey(nextVertex, newDistance)  # Lift the vertex up in the queue to maintain heap structure


def printRoute(target):
    if target.getPred():
        printRoute(target.getPred())
        print "%s To %s, %3d Km" % (
        target.getPred().getId(), target.getId(), target.getDistance() - target.getPred().getDistance())


if __name__ == '__main__':
    g = Graph()

    fileName, start, destination = raw_input().split()

    for line in readLines(fileName):
        words = line.split()
        g.addEdge(words[0], words[1], int(words[2]))
        g.addEdge(words[1], words[0], int(words[2]))

    target = g.getVertex(destination)
    dijkstra(g, g.getVertex(start), target)

    cost = target.getDistance()

    if cost == 9223372036854775807:
        print "Distance: Infinity"
        print "Route: \nNone"
    else:
        print "Distance: %d Km" % cost
        print "Route: "
        printRoute(target)