Delivery Route
Time limit1sMemory limit128 MB
Find the shortest 4-directional grid path that visits farms 1..N in order and back to farm 1, never stepping on any other farm's cell; output -1 if impossible.
- Level
Hard8 of 10
- Topics
- BFS, Shortest path, Geometry, Implementation
- Solved
- No attempts yet
Problem
After several years of record milk production, Farmer John now operates an entire network of farms (). Farm is located at position in the 2D plane; all farm positions are distinct, and both and are integers.
Farmer John needs your help planning his daily delivery route to bring supplies to the farms. Starting from farm 1, he plans to visit the farms in order (farm 1, then farm 2, then farm 3, and so on), and after visiting farm he returns to farm 1. It takes FJ one minute to make a single step north, south, east, or west. Moreover, FJ wants to visit each farm exactly once during his entire journey (except farm 1, which he of course visits twice). In other words, while travelling between two farms he may never step on the cell occupied by any other farm.
Please help FJ determine the minimum amount of time it will take him to complete his entire delivery route.
Input
- Line 1: the number of farms, .
- Lines 2..: line contains two space-separated integers and ().
Output
- Line 1: the minimum number of minutes FJ needs to complete his delivery route, or if there is no feasible route that visits every farm exactly once (except farm 1).
Hint
In the first example, FJ can complete his delivery route in 12 minutes: 2 minutes to go from farm 1 to farm 2, 5 minutes to go from farm 2 to farm 3 (circumventing farm 1), 3 minutes to go from farm 3 to farm 4, and then 2 minutes to return to farm 1.