751. Furthest Empty Plot From Buildings

You are given a map of a city represented as a square n×n grid. Each cell in the grid is either:

0 representing an empty plot of land, or 1 representing a building.

Your task is to find an empty plot of land such that the distance to the nearest building is maximized, and return this distance. If there are no buildings or no empty plots, return −1.

The distance between two locations (x1,y1) and (x2,y2) is calculated using the Manhattan distance formula: |x1-x2|+|y1-y2|

Example 1:

Input: grid=[[0,1,0],[0,0,0],[1,0,0]]

Output:2

Explanation:

The empty plot at position (1,2) is the farthest from any building, with a distance of 2.

Example 2:

Input: grid=[[0,0,1],[0,0,0],[0,0,1]]

Output:3

Explanation:

The empty plot at position (1,0) is the farthest from any building, with a distance of 3.

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • n == grid.length
  • n == grid[i].length
  • 1 <= n <= 100
  • grid[i][j] is 0 or 1

Fun Facts

0
class Solution {
public:
int farthestEmptyPlot(vector<vector<int>> grid) {
}
};
 
Test Case

Input:

Grid