Created
March 19, 2018 23:41
-
-
Save Shadid12/840a28789f4970aa15878311a77180fb to your computer and use it in GitHub Desktop.
This file contains 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
def findShortestRoute(self, start, end , weight, shortestRoute, visited=[]): | |
""" | |
Recursive function to calculate the shortest route | |
Args: | |
start (str): Starting city | |
end (str): Destination city | |
weight (weight): weight of the route | |
shortestRoute (int): shortest path so far | |
visited (str[]): array of visited nodes | |
Returns: | |
int: calclated weight of the shortest route | |
""" | |
# Check if start and end nodes exists in route table | |
if start in self.routesTable and end in self.routesTable: | |
visited.append(start) # mark start to visited | |
for adj in self.routesTable[start]: | |
if(adj == end or adj not in visited): | |
weight += self.routesTable[start][adj] | |
''' | |
If destination matches, we compare | |
weight of this route to shortest route | |
so far, and make appropriate switch | |
''' | |
if adj == end: | |
if shortestRoute == 0 or weight < shortestRoute: | |
shortestRoute = weight | |
visited.remove(start) | |
return shortestRoute | |
''' | |
If destination does not match, and | |
destination node has not yet been visited, | |
we recursively traverse destination node | |
''' | |
if adj not in visited: | |
shortestRoute = self.findShortestRoute(adj, end, weight, shortestRoute, visited) | |
weight -= self.routesTable[start][adj] | |
else: | |
return "No such route exists" | |
if start in visited: | |
visited.remove(start) | |
return shortestRoute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment