KatInterview

Best Meeting Point Across All Stations in a City Grid

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbfsgridshortest-path

Last updated

Tests multi-source BFS on a grid to find the open cell with the smallest total shortest-path distance to every station, respecting walls and blocked cells.

Problem

You are managing a city grid represented as an m × n matrix. Each cell holds one of three values:

  • 0: An open street where a meeting point can be established.
  • 1: A transit station that must be connected to the meeting point.
  • 2: A blocked zone that no route may pass through.

Your task is to choose a single open street cell (0) as the meeting point so that the combined shortest travel distance from that cell to every transit station (1) is as small as possible.

Travel is allowed only along the four cardinal directions (up, down, left, right), and only through open street cells (0). Routes may not pass through blocked zones (2) or other transit stations (1). Each step between adjacent cells counts as distance 1.

Return the minimum combined distance. If there is no open cell from which every station is reachable, return -1.

Constraints

  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 100
  • grid[i][j] is 0, 1, or 2
  • There is at least one transit station (1) in the grid

Examples

Example 1

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

Output: 7

Example 2

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

Output: -1

Hints

Hint 1

Instead of running a search from every open cell, think about flipping the direction: run a search outward from each station instead. The distances are symmetric, so you get the same values with far fewer total operations.

Hint 2

You need two accumulator grids: one that sums up the distances each open cell receives across all station searches, and one that counts how many stations actually reached that cell. A cell is only a valid meeting point if every station reached it.

Hint 3

Standard BFS (queue, visited array, distance incremented level by level) gives exact shortest distances on an unweighted grid. Expand only into cells whose value is 0, and skip anything already visited in the current search.