Invader Jina

Place two poison sources on empty cells of an N by M grid so that the maximum Manhattan distance from any village to its nearest source is minimized.

Medium6Brute forceMathPrefix sumBinary searchInterviewNo attempts yetTime limit2sMemory limit256 MB

Problem

The planet is an NN by MM grid. Each cell is either empty (00) or a village (11). You must place exactly 22 poison bags, each on an empty cell.

Every second, the poison spreads to the four neighboring cells (up, down, left, right). A poisoned village infects each adjacent village after 11 second, so the spread is equivalent to movement through every cell of the grid. A village at (x,y)(x, y) becomes poisoned at the smaller of its Manhattan distances to the two bags, and the time to poison every village is the maximum of those values over all villages. Find the placement that minimizes this maximum.

Rows are numbered from 00 to N1N-1 and columns from 00 to M1M-1, with the top-left cell at (0,0)(0, 0). The input always admits a placement.

Input

The first line contains two integers NN and MM separated by a space. (2N,M202 \le N, M \le 20)

Each of the following NN lines contains a string of length MM. Each character is 00 or 11, where 00 means an empty cell and 11 means a village.

Output

Print the minimum time in seconds needed to poison every village when the 22 poison bags are placed on the best empty cells.