LeetCode 0317. Shortest Distance from All Buildings Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0317. Shortest Distance from All Buildings

Description

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.

 

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

 

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.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def shortestDistance(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) q = deque() total = 0 cnt = [[0] * n for _ in range(m)] dist = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if grid[i][j] == 1: total += 1 q.append((i, j)) d = 0 vis = set() while q: d += 1 for _ in range(len(q)): r, c = q.popleft() for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: x, y = r + a, c + b if ( 0 <= x < m and 0 <= y < n and grid[x][y] == 0 and (x, y) not in vis ): cnt[x][y] += 1 dist[x][y] += d q.append((x, y)) vis.add((x, y)) ans = inf for i in range(m): for j in range(n): if grid[i][j] == 0 and cnt[i][j] == total: ans = min(ans, dist[i][j]) return -1 if ans == inf else ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !