LC: 317. Shortest Distance from All Buildings
https://leetcode.com/problems/shortest-distance-from-all-buildings/
317. Shortest Distance from All Buildings
You are given an m x n grid grid of values 0, 1, or 2, where:
each
0marks an empty land that you can pass by freely,each
1marks a building that you cannot pass through, andeach
2marks 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: 1Example 3:
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 100grid[i][j]is either0,1, or2.There will be at least one building in the
grid.
317. Shortest Distance from All Buildings:
The Essence:
Wenn man jedem Gebäude anfängt und alle Zellen durch Breitensuche traversiert, ist die erste Zelle, die von allen Gebäuden durchgelaufen wird, der kürzeste Punkt. Wenn es keine solche Zelle gibt, dann gibt es auch keine Lösung.
Details:
Für eine ausführliche Erläuterung und Umsetzung sehen Sie bitte das entsprechende PR nach.
Solutions:
Default Code:
Last updated