Minimize Grid Inconvenience by Adding One Delivery Center
AmazonSoftware Engineer · Online AssessmentLast updated
Add at most one delivery center to minimize the maximum Chebyshev distance from ordinary grid cells to their nearest center.
A binary grid represents delivery coverage: 1 marks a delivery center and 0 marks an ordinary location. The distance between cells (r1, c1) and (r2, c2) is the Chebyshev distance max(abs(r1 - r2), abs(c1 - c2)).
The grid's inconvenience is the largest distance from any ordinary location to its nearest delivery center. You may convert at most one 0 cell into a delivery center. Return the minimum possible inconvenience after this optional conversion.
Function Contract
Implement getMinInconvenience(grid) -> int, where grid is a rectangular integer matrix.
Return the optimal inconvenience value, not the position of the new center.
Constraints and Clarifications
1 <= number of rows <= 500.1 <= number of columns <= 500.- Every entry is
0or1. - Existing delivery centers remain in place.
- Distances depend only on coordinates; there are no obstacles or path restrictions.
- The grid may initially contain no delivery center. In that case, placing one center is allowed and makes the final distances well defined.
- As an explicit edge-case convention, a final grid with no ordinary locations has inconvenience
0. - Adding no center is permitted when the existing arrangement is already optimal.
Examples
grid = [[0, 0, 0, 1],
[0, 0, 0, 1]]
Output: 1
Converting (0, 0) to a center leaves every ordinary location within Chebyshev distance 1 of a center. Zero inconvenience is impossible because ordinary locations remain.
grid = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
Output: 2
Placing the center at (1, 1) achieves inconvenience 2. No single center can be within distance 1 of both the first and last columns.
Hints
Hint 1
Focus on locations that existing centers do not cover: For a proposed maximum distance, only some ordinary locations still need help. Determine whether one grid position could cover every such location under the stated distance formula.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.