Under construction

Still being built. Things may change

Invader Jina

Interview

Time limit2sMemory limit256 MB

Summary
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.
Level

Medium6 of 10

Topics
Brute force, Math, Prefix sum, Binary search
Solved
No attempts yet

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 N−1N-1 and columns from 00 to M−1M-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. (2≤N,M≤202 \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.

Examples2

  1. Example 1

    Input
    5 6
    110011
    000000
    000000
    011010
    000000
    
    Expected output
    3
    
  2. Example 2

    Input
    19 18
    001010001000011000
    000000100110010100
    000001000110110000
    001000000000000100
    000000010011000010
    100101010010000100
    010000110101100001
    000100001001101001
    101001110100100000
    001000100000010000
    010011101101000100
    100001100110010001
    010010110100000001
    001001000000100000
    000000000000101010
    101010000001101111
    011110000000000111
    000000001010100000
    001100010110000000
    
    Expected output
    12