As Far from Land as Possible

MediumGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an n x n grid where 1 is land and 0 is water. For each water cell, consider its **Manhattan distance** to the closest land cell (distance between (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|). Return the largest such distance over all water cells. If the grid contains no land or no water, return -1. Aim for O(n²) time.

Examples

Input: grid = [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
The center cell is distance 2 from every corner land cell.
Input: grid = [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
The bottom-right cell is 2 + 2 = 4 away from the only land cell.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems