KatInterview

Shortest Grid Path to Nearest Fulfillment Hub

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & GraphsBFSMulti-Source BFSGrid Traversal

Last updated

Find the minimum travel distance from every destination point to its closest source hub on a 2D grid using multi-source Breadth-First Search.

You are given a 2D grid represented as a list of strings, where each character denotes a cell type:

  • 'S': A fulfillment store (source)
  • 'H': A customer residence (destination)
  • '.': An open, traversable path
  • '#': An impassable barrier

Movement is permitted only in the four cardinal directions (up, down, left, right) across non-barrier cells ('S', 'H', and '.'). You can freely step onto or pass through other stores or residences.

For each residence ('H'), compute the shortest path distance (measured in number of steps) to the nearest fulfillment store ('S'). If a residence cannot be reached from any store, its distance is defined as -1.

Return a list of integers containing the minimum distance for each residence, ordered by the appearance of each 'H' in standard row-major order (scanning top to bottom, left to right).

Constraints

  • $0 \le \text{len(grid)} \le 500$
  • $0 \le \text{len(grid[r])} \le 500$ for all $r$
  • All strings in grid have the same length.
  • The grid contains only the characters 'S', 'H', '.'), and '#'.

Examples

Example 1

Input: grid_delivery_distances(['S..', '...', '..H'])

Output: [4]

Example 2

Input: grid_delivery_distances(['S#H', '...', 'H..'])

Output: [4, 2]

Example 3

Input: grid_delivery_distances(['H.H', '###', 'S..'])

Output: [-1, -1]

Example 4

Input: grid_delivery_distances(['...', '...'])

Output: []

Hints

Hint 1

Running an independent BFS from each residence can be too slow if there are many residences.

Hint 2

Consider reversing the search direction or starting BFS from all stores simultaneously.

Hint 3

Using a multi-source BFS allows you to compute the minimum distance from any store to every cell in a single pass of time O(rows * cols).