317. Shortest Distance from All Buildings
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find an empty land spot (marked with 0) to build a house such that the sum of distances to all buildings (marked with 1) is minimized. We can move up, down, left, or right, but cannot pass through buildings or obstacles (marked with 2). If no such spot exists, we should return -1.
Solution
Shortest Distance from All Buildings in Python
import collections
class Solution:
def shortestDistance(self, grid: list[list[int]]) -> int:
m, n = len(grid), len(grid[0])
# Store total distances and reach counts for each empty land
distance_sum = [[0] * n for _ in range(m)]
reach_count = [[0] * n for _ in range(m)]
total_buildings = 0
# Count total number of buildings
for r in range(m):
for c in range(n):
if grid[r][c] == 1:
total_buildings += 1
# Start BFS from each building
for r_start in range(m):
for c_start in range(n):
if grid[r_start][c_start] == 1:
q = collections.deque([(r_start, c_start, 0)])
visited = set([(r_start, c_start)])
while q:
r, c, dist = q.popleft()
# Explore neighbors
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
# Check if neighbor is a valid empty land and not visited
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 0 and (nr, nc) not in visited:
visited.add((nr, nc))
distance_sum[nr][nc] += dist + 1
reach_count[nr][nc] += 1
q.append((nr, nc, dist + 1))
min_dist = float('inf')
# Find the empty land that can reach all buildings with minimum total distance
for r in range(m):
for c in range(n):
if grid[r][c] == 0 and reach_count[r][c] == total_buildings:
min_dist = min(min_dist, distance_sum[r][c])
return min_dist if min_dist != float('inf') else -1
Shortest Distance from All Buildings in Java
class Solution {
public int shortestDistance(int[][] grid) {
if (grid == null || grid.length == 0) {
return -1;
}
int m = grid.length;
int n = grid[0].length;
int[][] distanceSum = new int[m][n];
int[][] reachCount = new int[m][n];
int totalBuildings = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
totalBuildings++;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
// Start BFS from each building
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{i, j});
boolean[][] visited = new boolean[m][n];
visited[i][j] = true;
int level = 0;
while (!queue.isEmpty()) {
int size = queue.size();
level++;
for (int k = 0; k < size; k++) {
int[] curr = queue.poll();
int r = curr[0];
int c = curr[1];
int[] dr = {0, 1, 0, -1};
int[] dc = {1, 0, -1, 0};
for (int move = 0; move < 4; move++) {
int nr = r + dr[move];
int nc = c + dc[move];
if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc] && grid[nr][nc] == 0) {
visited[nr][nc] = true;
distanceSum[nr][nc] += level;
reachCount[nr][nc]++;
queue.offer(new int[]{nr, nc});
}
}
}
}
}
}
}
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 0 && reachCount[i][j] == totalBuildings) {
minDistance = Math.min(minDistance, distanceSum[i][j]);
}
}
}
return minDistance == Integer.MAX_VALUE ? -1 : minDistance;
}
}
Shortest Distance from All Buildings in C++
class Solution {
public:
int shortestDistance(vector<vector<int>>& grid) {
int m = grid.size();
if (m == 0) return -1;
int n = grid[0].size();
vector<vector<int>> distance_sum(m, vector<int>(n, 0));
vector<vector<int>> reach_count(m, vector<int>(n, 0));
int total_buildings = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
total_buildings++;
}
}
}
int dr[] = {0, 1, 0, -1};
int dc[] = {1, 0, -1, 0};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
queue<pair<int, int>> q;
q.push({i, j});
vector<vector<int>> dist(m, vector<int>(n, -1));
dist[i][j] = 0;
int level = 0;
while (!q.empty()) {
int level_size = q.size();
level++;
for (int k = 0; k < level_size; ++k) {
pair<int, int> curr = q.front();
q.pop();
for (int move = 0; move < 4; ++move) {
int nr = curr.first + dr[move];
int nc = curr.second + dc[move];
if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0 && dist[nr][nc] == -1) {
dist[nr][nc] = level;
distance_sum[nr][nc] += level;
reach_count[nr][nc]++;
q.push({nr, nc});
}
}
}
}
}
}
}
int min_dist = INT_MAX;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0 && reach_count[i][j] == total_buildings) {
min_dist = min(min_dist, distance_sum[i][j]);
}
}
}
return min_dist == INT_MAX ? -1 : min_dist;
}
};
Shortest Distance from All Buildings in TypeScript
function shortestDistance(grid: number[][]): number {
const m = grid.length;
if (m === 0) return -1;
const n = grid[0].length;
const distanceSum: number[][] = Array(m).fill(0).map(() => Array(n).fill(0));
const reachCount: number[][] = Array(m).fill(0).map(() => Array(n).fill(0));
let totalBuildings = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
totalBuildings++;
}
}
}
const dr = [0, 1, 0, -1];
const dc = [1, 0, -1, 0];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
// Start BFS from each building
const queue: [number, number][] = [];
queue.push([i, j]);
const visited: boolean[][] = Array(m).fill(false).map(() => Array(n).fill(false));
visited[i][j] = true;
let level = 0;
while (queue.length > 0) {
const size = queue.length;
level++;
for (let k = 0; k < size; k++) {
const [r, c] = queue.shift()!;
for (let move = 0; move < 4; move++) {
const nr = r + dr[move];
const nc = c + dc[move];
if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc] && grid[nr][nc] === 0) {
visited[nr][nc] = true;
distanceSum[nr][nc] += level;
reachCount[nr][nc]++;
queue.push([nr, nc]);
}
}
}
}
}
}
}
let minDistance = Infinity;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 0 && reachCount[i][j] === totalBuildings) {
minDistance = Math.min(minDistance, distanceSum[i][j]);
}
}
}
return minDistance === Infinity ? -1 : minDistance;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.