Hole
InterviewTime limit2sMemory limit512 MB
Find the side length of the largest all-zero square in an n by n binary grid given by the positions of its ones.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Matrix
- Solved
- No attempts yet
Problem
A group of scientists want to monitor a huge forest. They plan to airdrop small sensors into the forest. Many conditions during the airdrop are unpredictable, so each sensor lands in a random location. After all sensors have landed, square regions that contain no sensor remain in the forest. Call such a region a hole.
Small holes are desirable, and airdropping a very large number of sensors achieves that. Sensors are expensive, though. So the scientists want to run a computer simulation to decide how many sensors to airdrop, so that the chance of a large hole is small. The simulation needs a subroutine that reads the locations of the sensors and outputs the size of the largest hole. The simulation repeats many times with different parameters, so the subroutine has to be fast. Writing that subroutine is your task.
Consider an array of 0s and 1s. There is a hole in at with width when both of the following hold.
- for every with and .
- and .
That is, every value inside the square at with width is 0. The indices of the array start from 0.
Given the array , find the width of the largest hole.
Input
The input represents the array .
The first line contains the width of the array , a positive integer of at most 1,024. The second line contains an integer , the number of 1s in the array. Then lines follow, one for each entry with value 1. Each line contains two integers and , which means .
Since may be as large as 1,024, your program has to run fast enough to handle arrays of that size.
Output
Print one integer, the width of the largest hole. If the array has no hole, print 0.
Hint
The figure below shows the array of the first example. The entry sits at row and column , and the arrow points to the location of .
In this array there is a hole of width 3 at , and no hole of width 4 at . The largest hole has width 5 and sits at . The highlighted square in the figure is that hole.

Several fast methods find the largest hole. Below are hints to two different methods.
Hint 1: Consider these two values.
- : the width of the largest hole that fits at
- : the width of the largest hole that fits at
What is the relationship between and ? If you know , is there a fast way to compute ?
Hint 2: Consider these two values.
- : the number of 1s inside the square at with width 7
- : the number of 1s inside the square at with width 7
What is the relationship between and ? If you know , is there a fast way to compute ?