Problem 615376 · easy · Phase 06 Heuristics & Optimization

Closest Shelf First

greedy construction · nearest neighbour · tie-breaking

A warehouse picker starts at the dock at (0, 0) and must visit every shelf in shelves, a list of (x, y) grid positions. The picker walks along the aisles, so the distance between two points is |x1 - x2| + |y1 - y2|.

The picker follows one simple rule: from where they stand, walk to the closest shelf not yet visited. When several unvisited shelves are equally close, pick the one with the smaller x; if that still ties, the smaller y; if two shelves stand at the same position, the one with the smaller index in shelves.

Write picking_order(shelves) that returns the indices of the shelves in the order the picker visits them.

Examples

Input:  shelves = [(3, 1), (1, 2), (2, 2), (0, 5)]
Output: [1, 2, 0, 3]
Explanation: from (0, 0) the distances are 4, 3, 4, 5, so shelf 1 comes first.
             From (1, 2): shelf 2 is 1 away, shelf 0 is 3 away, shelf 3 is 4 away.
             From (2, 2): shelf 0 (2 away) before shelf 3 (5 away).

Input:  shelves = [(2, 0), (0, 2), (1, 1)]
Output: [1, 2, 0]
Explanation: all three shelves are 2 away from the dock; (0, 2) has the smallest x.

Input:  shelves = [(4, 4), (1, 0), (4, 4), (0, 1)]
Output: [3, 1, 0, 2]
Explanation: shelves 0 and 2 share a position, so the smaller index goes first.

Constraints

  • 0 <= len(shelves) <= 600
  • 0 <= x, y <= 10**4, all integers

Goals

  • Build a complete route one greedy step at a time
  • Apply a precise tie-breaking rule with a sort key
  • Track the current position while choosing the next stop
Starting Python…