KatInterview

Minimum Steps to Collect All Treasure on a Grid

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & GraphsgraphsBFSgrid

Last 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:

SymbolMeaning
'.'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 S to 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 ≤ 50
  • 0 ≤ number of treasure chests ≤ 8
  • The grid contains exactly one 'S'
  • Grid cells are only '.', '#', 'S', or 'T'
  • Each string in grid has 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.