KatInterview

Optimal Empty Cell with Minimum Path Distance Sum

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbreadth-first-searchgraphsgrid-traversal

Last updated

Tests multi-source BFS to find an empty cell minimizing total shortest-path distance to all targets on a grid with obstacles.

You are given an m x n grid where each cell contains one of three values:

  • 0 represents an empty cell
  • 1 represents a target location
  • 2 represents a blocked cell (obstacle)

Your task is to find an empty cell that minimizes the sum of shortest walking distances to every target location. You can only move horizontally or vertically between adjacent empty cells; you cannot walk through targets or obstacles.

Return the minimum possible sum of distances. If no empty cell can reach all targets, return -1.

Constraints

  • 1 ≤ m, n ≤ 50
  • At least one target location exists in the grid
  • Distance is measured by the shortest path length, not Manhattan distance
  • An empty cell is valid only if every target location can reach it through empty cells

Examples

Example 1

Input: optimal_meeting_cell([[1, 0, 0], [0, 0, 0], [0, 0, 1]])

Output: 4

Example 2

Input: optimal_meeting_cell([[1, 0, 2], [2, 2, 2], [0, 0, 1]])

Output: -1

Hints

Hint 1

Consider running BFS from each target location rather than from every empty cell—this is more efficient when targets are sparse.

Hint 2

Track two pieces of information per cell: the total distance accumulated from all targets, and how many targets successfully reached that cell.

Hint 3

A cell is only valid if the count of targets that reached it equals the total number of targets in the grid.