Shortest Distance from All Buildings

Let’s create a function shortestDistance inside the given Solution class. We’ll perform a Breadth-First Search (BFS) from each building, and keep track of the sum of distances and reach count for each empty land.

Here’s the Python code to implement this logic:

from collections import deque
from typing import List

class Solution:
    def shortestDistance(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        buildings = 0

        # Initialize distance and reach count for each empty land
        distance_sum = [[0] * n for _ in range(m)]
        reach_count = [[0] * n for _ in range(m)]

        # BFS starting from building
        def bfs(i: int, j: int):
            visited = [[False] * n for _ in range(m)]
            visited[i][j] = True
            queue = deque([(i, j, 0)])
            while queue:
                x, y, dist = queue.popleft()
                for dx, dy in directions:
                    nx, ny = x + dx, y + dy
                    if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 0 and not visited[nx][ny]:
                        distance_sum[nx][ny] += dist + 1
                        reach_count[nx][ny] += 1
                        visited[nx][ny] = True
                        queue.append((nx, ny, dist + 1))

        # Iterate through the grid and start BFS from each building
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    buildings += 1
                    bfs(i, j)

        # Find the shortest distance where reach count equals number of buildings
        min_distance = float('inf')
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 0 and reach_count[i][j] == buildings:
                    min_distance = min(min_distance, distance_sum[i][j])

        return min_distance if min_distance != float('inf') else -1


  • For each building, we start a BFS, visiting only the empty lands (0s), and add up the distances and reach counts for each land.
  • We then iterate through the result and find the empty land with the minimum total distance that has been reached by all the buildings.
  • If no such land is found, we return -1.

The given examples will return the correct results, 7, 1, and -1, respectively.

Identifying Problem Isomorphism

“Shortest Distance from All Buildings” asks you to find a building that is shortest in total distance from all other buildings, considering obstacles that can affect the possible paths.

An isomorphic problem to this is “Cut Off Trees for Golf Event” (#675 on LeetCode). This problem involves finding the minimum total distance to cut down all the trees in a forest for a golf event. The trees are represented by a 2D grid with each cell having a positive integer that represents the height of the tree, and the distance is computed based on the number of steps needed to go from one cell to another.

The isomorphism lies in the concept of finding the minimum total distance in a 2D grid with obstacles. Both problems involve determining an optimal path that minimizes the total distance, considering the presence of obstacles in the grid. The algorithms for solving both problems typically involve breadth-first search or similar algorithms to find the shortest paths considering the constraints.

“Cut Off Trees for Golf Event” is more complex, since it involves not only finding the shortest distance, but also ordering the trees in non-descending order of height. On the other hand, “Shortest Distance from All Buildings” is simpler, focusing solely on finding the minimum total distance from a specific building to all others.

10 Prerequisite LeetCode Problems

“317. Shortest Distance from All Buildings” involves applying breadth-first search (BFS) in a grid. You need a good understanding of BFS, multi-source BFS, and 2D grid traversal to approach this problem.

Here are 10 problems to prepare for it:

  1. Number of Islands (LeetCode #200): This problem will help you understand basic grid traversal using depth-first search (DFS) or BFS.

  2. Walls and Gates (LeetCode #286): This problem introduces multi-source BFS in a grid, similar to the target problem.

  3. Flood Fill (LeetCode #733): A basic BFS problem on a 2D grid.

  4. 01 Matrix (LeetCode #542): This problem uses multi-source BFS to find distances in a grid.

  5. Rotting Oranges (LeetCode #994): This problem also involves a form of multi-source BFS.

  6. Perfect Squares (LeetCode #279): Although it’s not a grid problem, it helps understand BFS in the context of finding shortest paths or minimal operations.

  7. Word Ladder (LeetCode #127): This problem uses BFS to find the shortest transformation sequence from one word to another.

  8. Surrounded Regions (LeetCode #130): This problem will help you understand BFS for solving problems related to boundary elements in a grid.

  9. Open the Lock (LeetCode #752): This problem involves BFS in the context of finding the shortest path in a lock combination problem.

  10. Binary Tree Level Order Traversal (LeetCode #102): Even though it’s a tree problem, it involves BFS, which is a crucial concept in solving grid problems like the target one.

Problem Analysis and Key Insights

What are the key insights from analyzing the problem statement?

Problem Boundary

What is the scope of this problem?

How to establish the boundary of this problem?

Problem Classification

Problem Statement:You are given an m x n grid grid of values 0, 1, or 2, where:

each 0 marks an empty land that you can pass by freely, each 1 marks a building that you cannot pass through, and each 2 marks an obstacle that you cannot pass through. You want to build a house on an empty land that reaches all buildings in the shortest total travel distance. You can only move up, down, left, and right.

Return the shortest travel distance for such a house. If it is not possible to build such a house according to the above rules, return -1.

The total travel distance is the sum of the distances between the houses of the friends and the meeting point.

The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

Example 1:

Input: grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] Output: 7 Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2). The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7. Example 2:

Input: grid = [[1,0]] Output: 1 Example 3:

Input: grid = [[1]] Output: -1


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.

Analyze the provided problem statement. Categorize it based on its domain, ignoring ‘How’ it might be solved. Identify and list out the ‘What’ components. Based on these, further classify the problem. Explain your categorizations.

Distilling the Problem to Its Core Elements

Can you identify the fundamental concept or principle this problem is based upon? Please explain. What is the simplest way you would describe this problem to someone unfamiliar with the subject? What is the core problem we are trying to solve? Can we simplify the problem statement? Can you break down the problem into its key components? What is the minimal set of operations we need to perform to solve this problem?

Visual Model of the Problem

How to visualize the problem statement for this problem?

Problem Restatement

Could you start by paraphrasing the problem statement in your own words? Try to distill the problem into its essential elements and make sure to clarify the requirements and constraints. This exercise should aid in understanding the problem better and aligning our thought process before jumping into solving it.

Abstract Representation of the Problem

Could you help me formulate an abstract representation of this problem?

Given this problem, how can we describe it in an abstract way that emphasizes the structure and key elements, without the specific real-world details?


Are there any specialized terms, jargon, or technical concepts that are crucial to understanding this problem or solution? Could you define them and explain their role within the context of this problem?

Problem Simplification and Explanation

Could you please break down this problem into simpler terms? What are the key concepts involved and how do they interact? Can you also provide a metaphor or analogy to help me understand the problem better?


Given the problem statement and the constraints provided, identify specific characteristics or conditions that can be exploited to our advantage in finding an efficient solution. Look for patterns or specific numerical ranges that could be useful in manipulating or interpreting the data.

What are the key insights from analyzing the constraints?

Case Analysis

Could you please provide additional examples or test cases that cover a wider range of the input space, including edge and boundary conditions? In doing so, could you also analyze each example to highlight different aspects of the problem, key constraints and potential pitfalls, as well as the reasoning behind the expected output for each case? This should help in generating key insights about the problem and ensuring the solution is robust and handles all possible scenarios.

Provide names by categorizing these cases

What are the edge cases?

What are the key insights from analyzing the different cases?

Identification of Applicable Theoretical Concepts

Can you identify any mathematical or algorithmic concepts or properties that can be applied to simplify the problem or make it more manageable? Think about the nature of the operations or manipulations required by the problem statement. Are there existing theories, metrics, or methodologies in mathematics, computer science, or related fields that can be applied to calculate, measure, or perform these operations more effectively or efficiently?

Simple Explanation

Can you explain this problem in simple terms or like you would explain to a non-technical person? Imagine you’re explaining this problem to someone without a background in programming. How would you describe it? If you had to explain this problem to a child or someone who doesn’t know anything about coding, how would you do it? In layman’s terms, how would you explain the concept of this problem? Could you provide a metaphor or everyday example to explain the idea of this problem?

Problem Breakdown and Solution Methodology

Given the problem statement, can you explain in detail how you would approach solving it? Please break down the process into smaller steps, illustrating how each step contributes to the overall solution. If applicable, consider using metaphors, analogies, or visual representations to make your explanation more intuitive. After explaining the process, can you also discuss how specific operations or changes in the problem’s parameters would affect the solution? Lastly, demonstrate the workings of your approach using one or more example cases.

Inference of Problem-Solving Approach from the Problem Statement

Can you identify the key terms or concepts in this problem and explain how they inform your approach to solving it? Please list each keyword and how it guides you towards using a specific strategy or method.

How did you infer from the problem statement that this problem can be solved using ?

Simple Explanation of the Proof

I’m having trouble understanding the proof of this algorithm. Could you explain it in a way that’s easy to understand?

Stepwise Refinement

  1. Could you please provide a stepwise refinement of our approach to solving this problem?

  2. How can we take the high-level solution approach and distill it into more granular, actionable steps?

  3. Could you identify any parts of the problem that can be solved independently?

  4. Are there any repeatable patterns within our solution?

Solution Approach and Analysis

Given the problem statement, can you explain in detail how you would approach solving it? Please break down the process into smaller steps, illustrating how each step contributes to the overall solution. If applicable, consider using metaphors, analogies, or visual representations to make your explanation more intuitive. After explaining the process, can you also discuss how specific operations or changes in the problem’s parameters would affect the solution? Lastly, demonstrate the workings of your approach using one or more example cases.

Identify Invariant

What is the invariant in this problem?

Identify Loop Invariant

What is the loop invariant in this problem?

Thought Process

Can you explain the basic thought process and steps involved in solving this type of problem?

Explain the thought process by thinking step by step to solve this problem from the problem statement and code the final solution. Write code in Python3. What are the cues in the problem statement? What direction does it suggest in the approach to the problem? Generate insights about the problem statement.

Establishing Preconditions and Postconditions

  1. Parameters:

    • What are the inputs to the method?
    • What types are these parameters?
    • What do these parameters represent in the context of the problem?
  2. Preconditions:

    • Before this method is called, what must be true about the state of the program or the values of the parameters?
    • Are there any constraints on the input parameters?
    • Is there a specific state that the program or some part of it must be in?
  3. Method Functionality:

    • What is this method expected to do?
    • How does it interact with the inputs and the current state of the program?
  4. Postconditions:

    • After the method has been called and has returned, what is now true about the state of the program or the values of the parameters?
    • What does the return value represent or indicate?
    • What side effects, if any, does the method have?
  5. Error Handling:

    • How does the method respond if the preconditions are not met?
    • Does it throw an exception, return a special value, or do something else?

Problem Decomposition

  1. Problem Understanding:

    • Can you explain the problem in your own words? What are the key components and requirements?
  2. Initial Breakdown:

    • Start by identifying the major parts or stages of the problem. How can you break the problem into several broad subproblems?
  3. Subproblem Refinement:

    • For each subproblem identified, ask yourself if it can be further broken down. What are the smaller tasks that need to be done to solve each subproblem?
  4. Task Identification:

    • Within these smaller tasks, are there any that are repeated or very similar? Could these be generalized into a single, reusable task?
  5. Task Abstraction:

    • For each task you’ve identified, is it abstracted enough to be clear and reusable, but still makes sense in the context of the problem?
  6. Method Naming:

    • Can you give each task a simple, descriptive name that makes its purpose clear?
  7. Subproblem Interactions:

    • How do these subproblems or tasks interact with each other? In what order do they need to be performed? Are there any dependencies?

From Brute Force to Optimal Solution

Could you please begin by illustrating a brute force solution for this problem? After detailing and discussing the inefficiencies of the brute force approach, could you then guide us through the process of optimizing this solution? Please explain each step towards optimization, discussing the reasoning behind each decision made, and how it improves upon the previous solution. Also, could you show how these optimizations impact the time and space complexity of our solution?

Code Explanation and Design Decisions

  1. Identify the initial parameters and explain their significance in the context of the problem statement or the solution domain.

  2. Discuss the primary loop or iteration over the input data. What does each iteration represent in terms of the problem you’re trying to solve? How does the iteration advance or contribute to the solution?

  3. If there are conditions or branches within the loop, what do these conditions signify? Explain the logical reasoning behind the branching in the context of the problem’s constraints or requirements.

  4. If there are updates or modifications to parameters within the loop, clarify why these changes are necessary. How do these modifications reflect changes in the state of the solution or the constraints of the problem?

  5. Describe any invariant that’s maintained throughout the code, and explain how it helps meet the problem’s constraints or objectives.

  6. Discuss the significance of the final output in relation to the problem statement or solution domain. What does it represent and how does it satisfy the problem’s requirements?

Remember, the focus here is not to explain what the code does on a syntactic level, but to communicate the intent and rationale behind the code in the context of the problem being solved.

Coding Constructs

Consider the following piece of complex software code.

  1. What are the high-level problem-solving strategies or techniques being used by this code?

  2. If you had to explain the purpose of this code to a non-programmer, what would you say?

  3. Can you identify the logical elements or constructs used in this code, independent of any programming language?

  4. Could you describe the algorithmic approach used by this code in plain English?

  5. What are the key steps or operations this code is performing on the input data, and why?

  6. Can you identify the algorithmic patterns or strategies used by this code, irrespective of the specific programming language syntax?

Language Agnostic Coding Drills

Your mission is to deconstruct this code into the smallest possible learning units, each corresponding to a separate coding concept. Consider these concepts as unique coding drills that can be individually implemented and later assembled into the final solution.

  1. Dissect the code and identify each distinct concept it contains. Remember, this process should be language-agnostic and generally applicable to most modern programming languages.

  2. Once you’ve identified these coding concepts or drills, list them out in order of increasing difficulty. Provide a brief description of each concept and why it is classified at its particular difficulty level.

  3. Next, describe the problem-solving approach that would lead from the problem statement to the final solution. Think about how each of these coding drills contributes to the overall solution. Elucidate the step-by-step process involved in using these drills to solve the problem. Please refrain from writing any actual code; we’re focusing on understanding the process and strategy.

Targeted Drills in Python

Now that you’ve identified and ordered the coding concepts from a complex software code in the previous exercise, let’s focus on creating Python-based coding drills for each of those concepts.

  1. Begin by writing a separate piece of Python code that encapsulates each identified concept. These individual drills should illustrate how to implement each concept in Python. Please ensure that these are suitable even for those with a basic understanding of Python.

  2. In addition to the general concepts, identify and write coding drills for any problem-specific concepts that might be needed to create a solution. Describe why these drills are essential for our problem.

  3. Once all drills have been coded, describe how these pieces can be integrated together in the right order to solve the initial problem. Each drill should contribute to building up to the final solution.

Remember, the goal is to not only to write these drills but also to ensure that they can be cohesively assembled into one comprehensive solution.


Similar Problems

Can you suggest 10 problems from LeetCode that require similar problem-solving strategies or use similar underlying concepts as the problem we’ve just solved? These problems can be from any domain or topic, but they should involve similar steps or techniques in the solution process. Also, please briefly explain why you consider each of these problems to be related to our original problem.