Created
November 2, 2019 09:36
-
-
Save priyankvex/373843c204336a0100a9798e8c706e74 to your computer and use it in GitHub Desktop.
Complete the itinerary
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
from collections import defaultdict | |
class Solution(object): | |
def solve(self, trips): | |
# create a sorted adjacency list from the trips | |
graph = defaultdict(list) | |
for source, destination in trips: | |
graph[source].append(destination) | |
for source in graph.keys(): | |
graph[source] = sorted(graph[source], reverse=True) | |
route = [] | |
stack = ["J"] | |
while stack: | |
current_city = stack[-1] | |
while graph[current_city]: | |
current_city = graph[current_city].pop() | |
stack.append(current_city) | |
route.append(stack.pop()) | |
route = list(reversed(route)) | |
return route | |
if __name__ == "__main__": | |
trips = [ | |
("J", "A"), | |
("A", "D"), | |
("A", "B"), | |
("B", "C"), | |
("C", "A"), | |
("C", "E"), | |
("E", "C") | |
] | |
ans = Solution().solve(trips) | |
print(ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment