Taro Logo

Shortest Distance from All Buildings

#16 Most AskedHard
0 views
Topics:
ArraysGraphs

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.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0, 1, or 2.
  • There will be at least one building in the grid.

Solution


Clarifying Questions

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:

  1. What are the integer values used to represent empty plots, buildings, and obstacles in the 2D grid?
  2. What should be the exact return value if the grid contains no buildings, or if no empty plot can reach all the buildings?
  3. Can buildings and obstacles be traversed, or are they strictly impassable barriers?
  4. What are the maximum dimensions (rows and columns) of the 2D grid we should expect?
  5. If there are multiple empty plots that achieve the exact same minimum total distance, does it matter which one we base our return value on?

Brute Force Solution

Approach

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:

  1. Look at the map and identify every single empty spot where nobody currently lives.
  2. Pick the first empty spot to be your starting point.
  3. Take a walk from this chosen empty spot to the first house, counting every step you need to take.
  4. Continue walking from that same empty spot to every other house on the map, keeping a running total of all your steps.
  5. Write down this final grand total of steps for that specific empty spot.
  6. Move on to the next empty spot and repeat the entire walking process to every single house, recording its total distance as well.
  7. Do this for every possible empty spot on the entire map.
  8. Compare all the grand totals you wrote down and pick the empty spot with the smallest overall distance.

Code Implementation

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_distance

Big(O) Analysis

Time Complexity
O(R^2 * C^2) – Let R be the number of rows and C be the number of columns in the grid, meaning the total number of cells is N = R * C. For each empty land cell, which can be up to N cells, we perform a Breadth-First Search traversal to visit every house. Each BFS takes O(R * C) time in the worst case, and we might repeat this for every empty cell. This leads to approximately (R * C) * (R * C) operations, which simplifies to O(R^2 * C^2).
Space Complexity
O(R * C) – The auxiliary space is driven by multiple data structures used during the traversal from every empty spot to all houses. Specifically, we maintain a queue for breadth-first search, a visited matrix, and distance tracking matrices, where the grid dimensions are R rows and C columns. If we define N as the total number of cells in the grid, where N equals R times C, each of these structures scales linearly with N. Therefore, the total extra memory consumed by the queues and tracking matrices simplifies in Big O notation to O(N).

Optimal Solution

Approach

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

  1. Look at the map and identify every single building.
  2. Pick one building to start with and pretend you are walking outward in all four directions across the open spaces, keeping track of how many steps it takes to reach each spot.
  3. As you walk, record the walking distance from this specific building to every open space you visit.
  4. Repeat this walking exploration for every other building on the map, making sure each building keeps a running total of the steps it takes to reach all the open spaces.
  5. Ignore any open space that cannot be reached by every single building, because it is not a valid meeting point.
  6. After all buildings have finished their explorations, look at all the valid open spaces and find the one that has the smallest total walking distance from all the buildings combined.
  7. Declare that best open space as your final answer, or report that no valid spot exists if every open space was walled off from at least one building.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(M^2 * N^2) – Let the grid have dimensions M and N, meaning there are M * N total cells, which represents our input size. For every building on the grid, we perform a Breadth-First Search that can potentially visit every single cell, taking O(M * N) time per building. Since the number of buildings is at most proportional to the total number of cells (M * N), we multiply the number of buildings by the cost of each traversal. This leads to approximately (M * N) * (M * N) operations, which simplifies to the final Big O time complexity of O(M^2 * N^2).
Space Complexity
O(R * C) – The auxiliary space is driven by a 2D distance tracking grid and a 2D reachability count grid, both matching the map dimensions of R rows and C columns. Additionally, the breadth-first search queue stores grid coordinates, requiring up to O(R * C) memory in the worst-case scenario. We define N as the total number of cells, R times C, making the overall auxiliary space scale linearly with the grid size.

Edge Cases

Grid with zero buildings
How to Handle:
Return -1 immediately since no buildings exist to calculate a distance to.
Grid with zero empty plots
How to Handle:
Return -1 because there are no available spots to place a meeting building.
Grid with only one building and one empty plot
How to Handle:
Return the distance of 1 since the single empty plot reaches the only building.
Disconnected components where a building cannot reach an empty plot
How to Handle:
Track reachable building counts per empty cell and discard cells that cannot reach every building.
No valid empty plot can reach all buildings
How to Handle:
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
How to Handle:
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
How to Handle:
Use standard 64-bit integer types for distance accumulators to safely prevent arithmetic overflow.
Multiple valid empty plots with different distances
How to Handle:
Maintain a global minimum distance variable during traversal and update it whenever a smaller total distance is found.
0/21 completed