Problem 934
As Far from Land as Possible
Medium · 20 pts · Matrix, Breadth-First Search
Problem
In an N × N grid, 1 is land and 0 is water. Find a water cell whose Manhattan distance to the nearest land cell is as large as possible, and print that distance. Print -1 if the grid has no land or no water. Run a breadth-first search starting from all land cells at once; the last water cell reached is the farthest, and its BFS level is the answer.
Input
The first line contains N. Each of the next N lines is a row of N characters 0 or 1.
Output
Print the maximum distance, or -1.
Constraints
1 <= N <= 100
Example input
3 101 000 101
Example output
2
Explanation
In 101 / 000 / 101, the centre cell is 2 steps away from every corner land cell, which is the largest such distance. So the answer is 2.