You are given an m x n grid grid of values 0, 1, or 2, where:
0 represents an empty land which you can pass by freely.1 represents a building which you cannot pass through.2 represents an obstacle which you cannot pass through.You want to build a house on an empty land that reaches all buildings in the shortest amount of distance. You can only move up, down, left, and right.
Return the shortest distance for such a house. If it is not possible to build such a house according to the above rules, return -1.
The distance is the sum of the distances between the house and all the buildings.
Example 1:
Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] Output: 7 Explanation: Building a house at (1,2) if the shortest distance since all the buildings can be reached from there. The distance from (1,2) to the building at (0,0) is 1 + 1 = 2. The distance from (1,2) to the building at (0,4) is 1 + 3 = 4. The distance from (1,2) to the building at (2,2) is 1 + 0 = 1. The total distance is 2 + 4 + 1 = 7.
Example 2:
Input: grid = [[1,0]] Output: 1
Example 3:
Input: grid = [[1]] Output: -1
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 50grid[i][j] is either 0, 1, or 2.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you need to find an empty spot on a grid that is as close as possible to all the houses combined. The brute force approach involves walking from every single empty spot to every single house to see which spot results in the shortest total walking distance.
Here's how the algorithm would work step-by-step:
def shortest_distance(grid):
if not grid or not grid[0]:
return -1
row_count = len(grid)
col_count = len(grid[0])
empty_spots = []
houses = []
for row_index in range(row_count):
for col_index in range(col_count):
if grid[row_index][col_index] == 0:
empty_spots.append((row_index, col_index))
elif grid[row_index][col_index] == 1:
houses.append((row_index, col_index))
if not houses or not empty_spots:
return -1
min_total_distance = float('inf')
# We evaluate each empty spot individually to find its total distance to all houses
for empty_spot in empty_spots:
current_total_distance = 0
is_reachable_for_all = True
for house in houses:
queue = [(empty_spot[0], empty_spot[1], 0)]
visited = {empty_spot}
house_distance = -1
while queue:
current_row, current_col, current_dist = queue.pop(0)
if current_row == house[0] and current_col == house[1]:
house_distance = current_dist
break
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
next_row = current_row + dr
next_col = current_col + dc
if 0 <= next_row < row_count and 0 <= next_col < col_count and grid[next_row][next_col] != 2:
if (next_row, next_col) not in visited:
visited.add((next_row, next_col))
queue.append((next_row, next_col, current_dist + 1))
if house_distance == -1:
is_reachable_for_all = False
break
current_total_distance += house_distance
# Only update the minimum distance if this empty spot can reach every house
if is_reachable_for_all and current_total_distance < min_total_distance:
min_total_distance = current_total_distance
# Return the best distance found, or negative one if no valid empty spot exists
if min_total_distance == float('inf'):
return -1
return min_total_distanceInstead of measuring the distance from every empty spot to every building, the optimal strategy works in reverse by exploring outward from each building. This clever shortcut lets us quickly calculate how far every building is from all the open spaces in just a few efficient sweeps.
Here's how the algorithm would work step-by-step:
from collections import deque
def shortest_distance(grid):
if not grid or not grid[0]:
return -1
row_count = len(grid)
col_count = len(grid[0])
total_distance_grid = [[0] * col_count for _ in range(row_count)]
reach_count_grid = [[0] * col_count for _ in range(row_count)]
building_count = 0
# We collect all buildings first to iterate through them later for BFS expansions.
building_coordinates = []
for row_index in range(row_count):
for col_index in range(col_count):
if grid[row_index][col_index] == 1:
building_count += 1
building_coordinates.append((row_index, col_index))
direction_offsets = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for building_row, building_col in building_coordinates:
visited_grid = [[False] * col_count for _ in range(row_count)]
bfs_queue = deque([(building_row, building_col, 0)])
visited_grid[building_row][building_col] = True
while bfs_queue:
current_row, current_col, current_dist = bfs_queue.popleft()
for row_offset, col_offset in direction_offsets:
next_row = current_row + row_offset
next_col = current_col + col_offset
if 0 <= next_row < row_count and 0 <= next_col < col_count:
if grid[next_row][next_col] == 0 and not visited_grid[next_row][next_col]:
visited_grid[next_row][next_col] = True
total_distance_grid[next_row][next_col] += current_dist + 1
reach_count_grid[next_row][next_col] += 1
bfs_queue.append((next_row, next_col, current_dist + 1))
minimum_distance = float('inf')
# Only spots reached by every building are valid meeting points for our calculation.
for row_index in range(row_count):
for col_index in range(col_count):
if grid[row_index][col_index] == 0 and reach_count_grid[row_index][col_index] == building_count:
if total_distance_grid[row_index][col_index] < minimum_distance:
minimum_distance = total_distance_grid[row_index][col_index]
# Return -1 if no open space was reachable by all buildings simultaneously.
if minimum_distance == float('inf'):
return -1
return minimum_distance| Case | How to Handle |
|---|---|
| Grid with zero buildings | Return -1 immediately since no buildings exist to calculate a distance to. |
| Grid with zero empty plots | Return -1 because there are no available spots to place a meeting building. |
| Grid with only one building and one empty plot | Return the distance of 1 since the single empty plot reaches the only building. |
| Disconnected components where a building cannot reach an empty plot | Track reachable building counts per empty cell and discard cells that cannot reach every building. |
| No valid empty plot can reach all buildings | Return -1 after searching the entire grid and finding no empty plot with a matching building count. |
| Maximum-sized grid leading to Time Limit Exceeded | Run Breadth-First Search from each building rather than every empty plot to optimize traversal complexity. |
| Integer overflow from summing large distances in massive grids | Use standard 64-bit integer types for distance accumulators to safely prevent arithmetic overflow. |
| Multiple valid empty plots with different distances | Maintain a global minimum distance variable during traversal and update it whenever a smaller total distance is found. |