You are given a table of distances between cities. The cities are numbered .
For example, the distance table might look like this: Here the cities are . For instance, the distance between the cities and is . In the table, this distance is on the row of the column , as well as on the row of the column .
Your task is to find the shortest route that starts at the city , visits all other cities, and returns back into the city . If there are multiple routes of the same length, the selected route is the one, where the smallest possible city number is chosen at each step. Given the table above, the shortest route is with the length .
In a file visitall.py
, implement the function find_route
that takes the distance table as a parameter. The function should return the length of the route and one route of that length.
You may assume that the number of cities is in the range . The function should be efficient in all such cases.
def find_route(distances): # TODO if __name__ == "__main__": distances = [[0, 2, 2, 1, 8], [2, 0, 9, 1, 2], [2, 9, 0, 8, 3], [1, 1, 8, 0, 3], [8, 2, 3, 3, 0]] length, route = find_route(distances) print(length) # 9 print(route) # [1, 3, 5, 2, 4, 1] distances = [[0, 7, 5, 9, 6, 3, 1, 3], [7, 0, 3, 2, 3, 3, 7, 8], [5, 3, 0, 4, 2, 7, 7, 1], [9, 2, 4, 0, 2, 3, 2, 4], [6, 3, 2, 2, 0, 9, 5, 9], [3, 3, 7, 3, 9, 0, 4, 5], [1, 7, 7, 2, 5, 4, 0, 7], [3, 8, 1, 4, 9, 5, 7, 0]] length, route = find_route(distances) print(length) # 18 print(route) # [1, 7, 4, 6, 2, 5, 3, 8, 1]