Open One Wall to Speed Up Multi-Source Spread
Trees & GraphsAuto-graded · 20 test casesLast updated
Use multi-source BFS and brute force over single wall removals to minimize the time until every target is reached, with strict-improvement tie-breaking.
Fastest Spread with at Most One Wall Opened
A rectangular map is given as a grid of single-character strings. Each cell is one of:
'S': a source. Every source starts emitting at time0.'T': a target. Every target must eventually be reached.'B': a wall. Nothing can enter or pass through a wall.'.': open floor.
Each time unit, every reached cell passes the signal to its four neighbors (up, down, left, right), as long as the neighbor lies inside the grid and is not a wall. Source and target cells are ordinary passable cells. A cell's arrival time is the earliest time any signal reaches it, and sources have arrival time 0.
The finish time of a grid is the largest arrival time over all target cells. If some target is never reached, that grid has no finish time (it is infeasible).
You may open at most one wall, which turns that single 'B' cell into open floor. You can also open none. Choose the option with the smallest finish time.
Selection rules
- Prefer the smallest finish time among all feasible options (opening nothing, or opening any single wall).
- If opening nothing is feasible and no single wall opening gives a strictly smaller finish time, the answer is to open nothing.
- Otherwise, among the wall openings that reach the best finish time, choose the wall with the smallest row index, and then the smallest column index.
- If no option (including opening nothing) reaches all targets, there is no answer.
Function
Implement best_wall_to_open(grid) which returns a tuple (finish_time, (r, c)):
finish_timeis the best achievable finish time, and(r, c)is the 0-indexed position of the wall to open.- If no wall should be opened, return
(finish_time, (-1, -1)). - If no option reaches all targets, return
(-1, (-1, -1)).
Constraints
1 <= m, n <= 30, wheremis the number of rows andnthe number of columns.1 <= m * n <= 900- Every cell is one of
'S','T','B','.'. - The grid contains at least one
'S'and at least one'T'.
Examples
Example 1
Input: best_wall_to_open([['S', '.', 'B', 'T'], ['.', 'B', 'B', '.'], ['.', '.', '.', '.']])
Output: [3, [0, 2]]
Example 2
Input: best_wall_to_open([['S', '.', 'T'], ['.', '.', '.']])
Output: [2, [-1, -1]]
Hints
Hint 1
Fix a grid first: all sources start together at time 0, so one BFS seeded with every source gives each cell's earliest arrival time.
Hint 2
With at most 900 cells there are at most 900 walls, so you can afford one BFS for the unmodified grid plus one BFS per wall. Treat the opened wall as a parameter instead of editing the grid.
Hint 3
Handle selection carefully: when the unmodified grid is feasible, a wall is chosen only if it is strictly faster than that baseline; when the baseline is infeasible, any feasible opening counts, and ties go to the smallest (row, column).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task splits into two parts.
1. Evaluate a single fixed grid. Every move costs one time unit and all sources start together, so a cell's arrival time is its shortest distance to the nearest source. A multi-source BFS computes this: put every 'S' in the queue at distance 0 and expand level by level. The finish time is the maximum distance over all targets. If any target keeps distance -1, the grid is infeasible.
2. Choose the wall. There are at most 900 cells, so at most 900 walls. We can try every option:
- Run the BFS once with nothing opened (the baseline).
- Run the BFS once per wall, treating only that wall as passable. The grid is never modified; the BFS simply checks whether a neighbor equals the opened coordinate.
Then apply the selection rules:
- If the baseline is feasible, a wall is chosen only when it gives a strictly smaller time. Otherwise the answer is
(baseline, (-1, -1)). - If the baseline is infeasible, every feasible opening is a candidate. The smallest time wins, with ties broken by the smallest
(r, c). - If nothing is feasible, return
(-1, (-1, -1)).
Walls are scanned in row-major order, which is already ascending (r, c). When the baseline is feasible, only strict improvements replace the current best, so the first wall reaching the best time is kept, which is the smallest. When the baseline is infeasible, the code compares tuples explicitly on ties.
Why it is correct
- BFS on a unit-cost graph discovers each cell at its minimum distance, and seeding all sources together is equivalent to a virtual super-source joined to each source with cost 0. So the arrival times are exact.
- The finish time is the maximum arrival time over targets, and an unreached target makes the configuration invalid.
- The optimal answer is one of the (number of walls + 1) configurations, and all of them are evaluated exactly, so taking the best under the stated rules is correct.
Complexity
- Time: O(W · m · n), where W is the number of walls. In the worst case this is about 900 × 900 = 810,000 cell visits.
- Space: O(m · n) for the distance table and queue, which are rebuilt for each BFS.
Reference solution
from collections import deque
from typing import List, Tuple
def best_wall_to_open(grid: List[List[str]]) -> Tuple[int, Tuple[int, int]]:
m = len(grid)
n = len(grid[0])
sources = []
targets = []
walls = []
for r in range(m):
for c in range(n):
cell = grid[r][c]
if cell == 'S':
sources.append((r, c))
elif cell == 'T':
targets.append((r, c))
elif cell == 'B':
walls.append((r, c))
def finish_time(opened):
dist = [[-1] * n for _ in range(m)]
q = deque()
for r, c in sources:
dist[r][c] = 0
q.append((r, c))
while q:
r, c = q.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if not (0 <= nr < m and 0 <= nc < n):
continue
if (nr, nc) == opened or grid[nr][nc] != 'B':
if dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
q.append((nr, nc))
worst = 0
for r, c in targets:
if dist[r][c] == -1:
return None
worst = max(worst, dist[r][c])
return worst
baseline = finish_time(None)
best_time = baseline if baseline is not None else float('inf')
best_wall = None
for wall in walls: # row-major order
t = finish_time(wall)
if t is None:
continue
if t < best_time:
best_time = t
best_wall = wall
elif t == best_time and baseline is None:
if best_wall is None or wall < best_wall:
best_wall = wall
if best_time == float('inf'):
return (-1, (-1, -1))
if baseline is not None and best_time == baseline:
return (baseline, (-1, -1))
return (best_time, best_wall)