1492. Widest Drone Passage

A warehouse floor is described by the matrix grid: 0 marks a free cell and 1 marks a blocked cell. A square delivery drone covers k by k cells and begins with its top-left cell on cell (0, 0). It must reach the position where its bottom-right cell sits on the last cell, (m-1, n-1). In one step it slides by exactly one cell up, down, left or right, and at every moment all k * k cells under it must be free and inside the floor.

Return the largest k for which such a journey exists, or 0 if even a drone covering a single cell cannot make it. A larger drone can only succeed if every smaller one can, so the answer is the unique largest successful size and no tie-break is needed. Use a binary search on k, a 2-D prefix sum for block checks and an iterative breadth-first search, for O(m n log min(m, n)) time and O(m n) space.

Example 1

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

The goal cell is blocked, so even a 1 by 1 drone cannot finish: the answer is 0.

Example 2

Input:
grid = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
Output:
3
Explanation:

The floor is empty and only 3 rows exist, so the biggest drone is 3 by 3, which fits and can slide along.

Example 3

Input:
grid = [[0,0,0,0],[0,0,0,1],[0,0,0,0],[0,0,0,0]]
Output:
2
Explanation:

A 2 by 2 drone can slide down the left side and along the bottom to the end, but a 3 by 3 drone would have to cover the blocked cell in its final position.

Constraints

1 ≤ m, n

m * n ≤ 105

grid[i][j] is 0 or 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(m n log min(m, n))
Space
O(m n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…