KatInterview

Fewest Planks Across a Portal-Linked Board

Trees & GraphsAuto-graded · 20 test cases
HardAuto-gradedTrees & Graphs0-1 BFSshortest pathgrid

Last updated

Find the cheapest route on a grid with free, paid and blocked cells plus same-numbered teleport cells, which calls for 0-1 BFS and care with teleport expansion.

Fewest Planks Across a Portal-Linked Board

You are given a rectangular board board with m rows and n columns, a starting cell origin = [r, c] and a destination cell goal = [r, c]. You want to travel from origin to goal while placing as few planks as possible.

Each cell holds one of these values:

  • -1: a wall. You can never enter or stand on it.
  • 0: a gap. Standing on it requires placing one plank on that cell.
  • 1: solid ground. Entering it costs 0 planks.
  • 2 to 9: a portal. Entering it costs 0 planks. All portals that share the same number are connected to each other. While standing on a portal, you may jump to any other cell with the same number at a cost of 0 planks.

Movement

  • From any cell you may step to one of its four neighbours (up, down, left, right), as long as the neighbour is inside the board and is not a wall.
  • A portal jump is only possible from a cell that is itself a portal, and it lands on another portal with the same number.
  • The cost of a step is determined by the cell you enter: 1 if it is a gap, otherwise 0. Jumps cost 0.
  • The starting cell is treated specially. If origin is a gap, you must place a plank on it, which costs 1. Otherwise the starting cell costs 0.

Task

Return the minimum total number of planks needed to get from origin to goal, or -1 if the goal cannot be reached.

Special cases

  • If origin equals goal, the answer is 1 when that cell is a gap and 0 when it is solid ground or a portal.
  • If either origin or goal is a wall, return -1.
  • Boards can be completely filled with portals of the same number, so your solution must not examine every pair of matching portals.

Constraints

  • m == len(board), n == len(board[0])
  • 1 <= m, n <= 500
  • Every board[r][c] is an integer from -1 to 9.
  • 0 <= origin[0], goal[0] < m and 0 <= origin[1], goal[1] < n

Examples

Example 1

Input: fewest_planks([[1, 0, -1], [0, 2, 0], [-1, 0, 2]], [0, 0], [2, 2])

Output: 1

Example 2

Input: fewest_planks([[0, -1], [-1, 1]], [0, 0], [1, 1])

Output: -1

Hints

Hint 1

Every move costs either 0 or 1, and the cost depends only on the cell being entered. Which shortest-path algorithm is built for exactly these weights?

Hint 2

With a deque, push zero-cost moves to the front and one-cost moves to the back. Remember to charge 1 up front if the starting cell is a gap.

Hint 3

Connecting every pair of equal portals is far too slow on a board full of the same number. Group portal cells by number and use the fact that nodes are popped in non-decreasing distance order, so each group needs to be expanded only the first time any of its members is popped.