Minimum Steps to Collect All Treasure on a Grid
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests BFS shortest-path reasoning on a grid by finding the minimum steps to collect all treasure chests from a starting position, visiting each chest at least once.
Minimum Steps to Collect All Treasure on a Grid
You are given a rectangular grid represented as a list of strings. Each cell is one of:
| Symbol | Meaning |
|---|---|
'.' | Empty passable cell |
'#' | Wall (impassable) |
'S' | Your starting position |
'T' | A treasure chest |
You must collect every treasure chest on the grid. You may move one step at a time in the four cardinal directions (up, down, left, right). You cannot step on walls.
Return the minimum total number of steps required to collect all treasure chests (i.e., visit every 'T' cell at least once), starting from 'S'.
If it is impossible to collect all treasures (some chest is unreachable), return -1.
Key details
- You do not need to return to
'S'after collecting all chests. - You may pass through a cell that previously held a chest; the chest is gone but the cell remains passable.
- The grid always contains exactly one
'S'. - There may be zero or more
'T'cells. - If there are zero treasure chests, return
0. - The optimal strategy is to chain BFS distances: find the shortest path from
Sto the nearest uncollected chest, then from there to the next nearest, and so on — but because the number of chests is small (≤ 8), you should consider all orderings of chest visits and return the minimum total distance across all orderings.
Constraints
1 ≤ rows, cols ≤ 500 ≤ number of treasure chests ≤ 8- The grid contains exactly one
'S' - Grid cells are only
'.','#','S', or'T' - Each string in
gridhas the same length
Examples
Example 1
Input: min_steps_collect_treasure(['S..T', '####', '....'])
Output: 3
Example 2
Input: min_steps_collect_treasure(['S.#', '.#T', '...'])
Output: 5
Example 3
Input: min_steps_collect_treasure(['ST', 'TT'])
Output: 3
Hints
Hint 1
First compute the BFS shortest distance between every pair of key points (S and each T). If any two key points have no path between them, return -1 immediately.
Hint 2
With at most 8 treasure chests there are at most 8! = 40320 orderings — enumerate all permutations of chests and sum up the pairwise distances for each ordering, keeping the minimum.
Hint 3
Use a bitmask DP over the set of collected treasures to solve the ordering problem in O(2^n * n^2) instead of O(n!), which is cleaner and faster even though both work within the constraints.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
High-level idea
The problem has two layers:
- Grid navigation — movement is on a grid with walls, so shortest paths between cells require BFS (not simple Manhattan distance).
- Ordering — with up to 8 treasures, we need the best order to visit them all. This is essentially a small Travelling Salesman Problem (TSP).
Step 1 — BFS between key points
Identify all "key points": the start cell S and every treasure cell T. Run a standard 4-directional BFS from each key point to build a pairwise distance table d[i][j]. Any pair with no path gets distance ∞.
This costs O(K × R × C) where K ≤ 9 key points, R rows, C columns — well within limits.
Step 2 — Bitmask DP (TSP on key points)
With at most 8 treasures there are at most 2^8 = 256 subsets and 8 "current position" choices, giving a state space of 256 × 8 = 2048 states.
Define:
dp[mask][i]= minimum steps to have collected exactly the treasures encoded inmask, currently standing at treasurei.
Base cases: dp[1<<(i-1)][i] = d[0][i] for each treasure i (travel directly from start).
Transition: For each state (mask, i), for each uncollected treasure j:
dp[mask | (1<<(j-1))][j] = min(..., dp[mask][i] + d[i][j])
Answer: min over i of dp[full_mask][i], where full_mask = (1<<n)-1.
If the answer remains ∞, return -1.
Correctness
BFS gives exact shortest paths on the unweighted grid. The bitmask DP correctly explores all orderings of treasure collection and keeps only the minimum-cost one. Returning -1 when the answer is ∞ covers cases where a wall completely separates a treasure from the rest of the grid.
Complexity
- Time: O(K × R × C) for BFS + O(2^K × K²) for DP, where K ≤ 9, R,C ≤ 50. Total ≈ O(22,500 + 18,432) — very fast.
- Space: O(R × C + 2^K × K) for BFS visited sets and DP table.
Reference solution
from typing import List
from collections import deque
def min_steps_collect_treasure(grid: List[str]) -> int:
rows = len(grid)
cols = len(grid[0])
start = None
treasures = []
for r in range(rows):
for c in range(cols):
if grid[r][c] == 'S':
start = (r, c)
elif grid[r][c] == 'T':
treasures.append((r, c))
n = len(treasures)
if n == 0:
return 0
def bfs(src):
dist = {src: 0}
q = deque([src])
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 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != '#' and (nr,nc) not in dist:
dist[(nr,nc)] = dist[(r,c)] + 1
q.append((nr,nc))
return dist
key_points = [start] + treasures
num_keys = n + 1
d = [[float('inf')] * num_keys for _ in range(num_keys)]
for i in range(num_keys):
dist_map = bfs(key_points[i])
for j in range(num_keys):
if key_points[j] in dist_map:
d[i][j] = dist_map[key_points[j]]
INF = float('inf')
dp = [[INF] * (n + 1) for _ in range(1 << n)]
for i in range(1, n + 1):
cost = d[0][i]
mask = 1 << (i - 1)
if cost < dp[mask][i]:
dp[mask][i] = cost
for mask in range(1, 1 << n):
for i in range(1, n + 1):
if dp[mask][i] == INF:
continue
if not (mask >> (i - 1) & 1):
continue
for j in range(1, n + 1):
if mask >> (j - 1) & 1:
continue
new_mask = mask | (1 << (j - 1))
new_cost = dp[mask][i] + d[i][j]
if new_cost < dp[new_mask][j]:
dp[new_mask][j] = new_cost
full_mask = (1 << n) - 1
ans = min(dp[full_mask][i] for i in range(1, n + 1))
return ans if ans < INF else -1