Problem 299542 · hard · Phase 02 Linear Data Structures

Parcel on the Wrap-Around Belts

2d-lists · simulation · cycle detection · hash maps

A sorting floor is a grid of belt tiles given as a list of equal-length strings belts. Each character is an arrow: '>' (right), '<' (left), '^' (up) or 'v' (down). The floor wraps around: moving right from the last column lands in column 0 of the same row, moving down from the last row lands in row 0 of the same column, and likewise for left and up.

A parcel starts on tile (r, c). Each step, it moves one tile in the direction of the arrow on the tile it is standing on. Return a list [row, col, seen], where (row, col) is the parcel's tile after exactly k steps and seen is the number of different tiles it has stood on during those steps, counting the start tile and the final tile.

Examples

Input:  belts = [">v", "^<"], r = 0, c = 0, k = 5
Output: [0, 1, 4]
Explanation: (0,0) -> (0,1) -> (1,1) -> (1,0) -> (0,0) -> (0,1).

Input:  belts = [">>^", "^<<", ">>^"], r = 2, c = 0, k = 10
Output: [1, 2, 9]
Explanation: (2,0) -> (2,1) -> (2,2) -> (1,2) -> (1,1) -> (1,0) -> (0,0) -> (0,1) -> (0,2),
then up from the top row wraps to (2,2), then (1,2).

Input:  belts = [">>^", "^<<", ">>^"], r = 2, c = 0, k = 10**18
Output: [0, 2, 9]

Constraints

  • 1 <= len(belts), len(belts[0]) <= 300
  • 0 <= r < len(belts), 0 <= c < len(belts[0])
  • 0 <= k <= 10**18
  • Stepping k times is far too slow for the largest k.

Goals

  • Simulate movement on a grid whose edges wrap around
  • Detect the first repeated tile with a dict of step numbers
  • Jump ahead through the loop with modular arithmetic
Starting Python…