Browser tab content: Problem List 0 Debugging... Run Submit 00:00:00 Description…
- User
Browser tab content: Problem List 0 Debugging... Run Submit 00:00:00 Description Editorial Editorial Solutions Solutions Submissions Submissions Debugger Debugger Code Note Note Testcase Testcase Test Result 317. Shortest Distance from All Buildings Hard Topics Companies
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
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. Seen this question in a real interview before? 1/5 Yes No Accepted 186.7K Submissions 428.5K Acceptance Rate 43.6% Topics Array Breadth-First Search Matrix Companies 0 - 3 months Meta 4 DoorDash 3 Apple 2 0 - 6 months Google 3 Amazon 2 Zenefits 2 6 months ago Snap 3 ByteDance 2 TikTok 2 Similar Questions Walls and Gates Medium Best Meeting Point Hard As Far from Land as Possible Medium Discussion (30) Choose a type Preview Comment 💡 Discussion Rules
-
Please don't post any solutions in this discussion.
-
The problem discussion is for asking questions about the problem or for sharing tips - anything except for solutions.
-
If you'd like to share your solution for feedback and ideas, please head to the solutions tab and post it there.
Sort by:Best No comments yet. 1 2 3 Copyright ©️ 2024 LeetCode All rights reserved 1.9K 30 19 Online Java Auto 1 2 3 4 5 class Solution { public int shortestDistance(int[][] grid) { } } Saved Ln 4, Col 6 Wrong Answer Runtime: 0 ms Case 1 Case 2 Case 3 Input grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] Output -1 Expected 7 Contribute a testcase Input 1 2 3 [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] [[1,0]] [[1]] Output 1 2 3 -1 1 -1 Expected 1 2 3 7 1 -1
-
- Assistant