Fewest Planks Across a Portal-Linked Board
Trees & GraphsAuto-graded · 20 test casesLast 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.2to9: 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
originis 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
originequalsgoal, the answer is1when that cell is a gap and0when it is solid ground or a portal. - If either
originorgoalis 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-1to9. 0 <= origin[0], goal[0] < mand0 <= 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model each non-wall cell as a graph node. The cost of an edge depends on the cell it enters: 1 for a gap, 0 for ground or a portal. A jump between equal portals costs 0. Because every edge weight is 0 or 1, 0-1 BFS is enough, and no heap is needed.
Use a deque of cells:
- When a relaxation uses a 0-cost edge, push the cell to the front.
- When it uses a 1-cost edge, push the cell to the back.
This keeps the deque ordered by distance, so cells are popped in non-decreasing distance order, as in Dijkstra's algorithm, but each operation is O(1). The starting distance is 1 if the start is a gap and 0 otherwise.
Avoiding the quadratic jump trap
Adding an edge between every pair of equal portals can create billions of edges on a board filled with one number. Instead:
- Collect the coordinates of each portal number in a single pass over the board.
- The first time any portal of number
kis popped, relax every cell in that group to the current distance (cost 0) and markkas used. - Never expand that group again.
This is correct because pops come out in non-decreasing distance order. The first popped portal of number k has the smallest distance of any portal of number k. A later portal of the same number could only offer an equal or larger distance, so repeating the expansion would never improve anything.
Why it is correct
- The deque only ever holds distances
dandd+1, with thedentries in front. This preserves Dijkstra-style ordering. - Because edge weights are non-negative, the goal's distance is final when it is first popped, so we can return immediately.
- A cell can be queued more than once. The current best distance is read when the cell is popped, and outdated entries fail every later
<comparison, so they do no harm. - If the deque empties without popping the goal, the goal is unreachable and the answer is
-1. - Walls at the start or goal are rejected up front.
origin == goalreturns the starting distance, which is 1 for a gap and 0 otherwise.
Complexity
- Time: O(m·n). Each cell is queued a bounded number of times, with 4 neighbour checks per pop, and each portal group is scanned once.
- Space: O(m·n) for the distance table, the portal groups and the deque.
Reference solution
from collections import defaultdict, deque
from typing import List
def fewest_planks(board: List[List[int]], origin: List[int], goal: List[int]) -> int:
rows, cols = len(board), len(board[0])
sr, sc = origin
gr, gc = goal
if board[sr][sc] == -1 or board[gr][gc] == -1:
return -1
# Group portal cells by their number.
groups = defaultdict(list)
for r in range(rows):
for c in range(cols):
v = board[r][c]
if v >= 2:
groups[v].append((r, c))
big = rows * cols + 1
dist = [[big] * cols for _ in range(rows)]
dist[sr][sc] = 1 if board[sr][sc] == 0 else 0
dq = deque([(sr, sc)])
used_groups = set()
while dq:
r, c = dq.popleft()
cur = dist[r][c]
if (r, c) == (gr, gc):
return cur
v = board[r][c]
if v >= 2 and v not in used_groups:
used_groups.add(v)
for pr, pc in groups[v]:
if cur < dist[pr][pc]:
dist[pr][pc] = cur
dq.appendleft((pr, pc))
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != -1:
w = 1 if board[nr][nc] == 0 else 0
nd = cur + w
if nd < dist[nr][nc]:
dist[nr][nc] = nd
if w == 0:
dq.appendleft((nr, nc))
else:
dq.append((nr, nc))
return -1