|
| 1 | +<p>You are given an <code>m x n</code> grid <code>grid</code> of values <code>0</code>, <code>1</code>, or <code>2</code>, where:</p> |
| 2 | + |
| 3 | +<ul> |
| 4 | + <li>each <code>0</code> marks <strong>an empty land</strong> that you can pass by freely,</li> |
| 5 | + <li>each <code>1</code> marks <strong>a building</strong> that you cannot pass through, and</li> |
| 6 | + <li>each <code>2</code> marks <strong>an obstacle</strong> that you cannot pass through.</li> |
| 7 | +</ul> |
| 8 | + |
| 9 | +<p>You want to build a house on an empty land that reaches all buildings in the <strong>shortest total travel</strong> distance. You can only move up, down, left, and right.</p> |
| 10 | + |
| 11 | +<p>Return <em>the <strong>shortest travel distance</strong> for such a house</em>. If it is not possible to build such a house according to the above rules, return <code>-1</code>.</p> |
| 12 | + |
| 13 | +<p>The <strong>total travel distance</strong> is the sum of the distances between the houses of the friends and the meeting point.</p> |
| 14 | + |
| 15 | +<p> </p> |
| 16 | +<p><strong class="example">Example 1:</strong></p> |
| 17 | +<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/buildings-grid.jpg" style="width: 413px; height: 253px;" /> |
| 18 | +<pre> |
| 19 | +<strong>Input:</strong> grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]] |
| 20 | +<strong>Output:</strong> 7 |
| 21 | +<strong>Explanation:</strong> Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2). |
| 22 | +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. |
| 23 | +So return 7. |
| 24 | +</pre> |
| 25 | + |
| 26 | +<p><strong class="example">Example 2:</strong></p> |
| 27 | + |
| 28 | +<pre> |
| 29 | +<strong>Input:</strong> grid = [[1,0]] |
| 30 | +<strong>Output:</strong> 1 |
| 31 | +</pre> |
| 32 | + |
| 33 | +<p><strong class="example">Example 3:</strong></p> |
| 34 | + |
| 35 | +<pre> |
| 36 | +<strong>Input:</strong> grid = [[1]] |
| 37 | +<strong>Output:</strong> -1 |
| 38 | +</pre> |
| 39 | + |
| 40 | +<p> </p> |
| 41 | +<p><strong>Constraints:</strong></p> |
| 42 | + |
| 43 | +<ul> |
| 44 | + <li><code>m == grid.length</code></li> |
| 45 | + <li><code>n == grid[i].length</code></li> |
| 46 | + <li><code>1 <= m, n <= 50</code></li> |
| 47 | + <li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code>, or <code>2</code>.</li> |
| 48 | + <li>There will be <strong>at least one</strong> building in the <code>grid</code>.</li> |
| 49 | +</ul> |
0 commit comments