Problem 567007 · medium · Phase 05 Advanced Algorithms & Graphs

Redirect the Conveyor Tiles

graphs · 0-1 BFS · grid · state space

A factory floor is a grid of conveyor tiles given as a list of equal-length strings belts. Each character is an arrow: '>' (right), '<' (left), '^' (up) or 'v' (down). A parcel placed on a tile moves one tile in the direction of its arrow. An arrow may point off the floor.

Before switching the belts on, you may repaint any tiles to point in a different direction; each repainted tile costs 1. Return the minimum number of repaints so that a parcel placed on the top-left tile eventually arrives at the bottom-right tile.

Examples

Input:  belts = [">>>",
                 "<<<",
                 ">>>"]
Output: 2
Explanation: e.g. repaint (0,2) and (1,2) to 'v': the parcel runs right, down, down.

Input:  belts = ["v",
                 "v",
                 "^"]
Output: 0

Constraints

  • 1 <= rows, cols and rows * cols <= 4 * 10**4
  • Target O(rows * cols) time.

Goals

  • Turn 'follow the arrow' and 'repaint the arrow' into 0- and 1-cost edges
  • Run 0-1 BFS from the top-left tile
  • Handle arrows that point off the grid
Starting Python…