Problem 673681 · easy · Phase 06 Heuristics & Optimization

Try Every Order

exhaustive search · permutations · travelling salesman

A street-food cart starts its evening at stop 0, must visit every other stop exactly once and then return to where it started. stops is a list of (x, y) points and the cart drives in straight lines between them.

Write shortest_loop(stops) that returns the length of the shortest such closed loop, rounded to 2 decimals. With a single stop the loop has length 0.0.

Examples

Input:  stops = [(0, 0), (4, 3), (0, 3), (4, 0)]
Output: 14.0
Explanation: visiting them in the listed order crosses the middle twice (5 + 4 + 5 + 4 = 18);
             going round the rectangle 0 -> 2 -> 1 -> 3 -> 0 gives 3 + 4 + 3 + 4 = 14.

Input:  stops = [(0, 0), (3, 4)]
Output: 10.0
Explanation: there and back again.

Input:  stops = [(5, 5)]
Output: 0.0

Constraints

  • 1 <= len(stops) <= 9
  • coordinates are integers between -1000 and 1000; stops may coincide

Goals

  • Enumerate every visiting order with itertools.permutations
  • Fix the starting stop so rotations of the same loop are not counted again
  • See how fast the number of orders grows with the number of stops
Starting Python…