#ABC296H. [ABC296Ex] Unite

[ABC296Ex] Unite

Score : 600600 points

Problem Statement

We have a grid with NN rows and MM columns, where each square is painted black or white. Here, at least one square is painted black. The initial state of the grid is given as NN strings S1,S2,,SNS_1,S_2,\ldots,S_N of length MM. The square at the ii-th row from the top and jj-th column from the left is painted black if the jj-th character of SiS_i is #, and white if it is ..

Takahashi wants to repaint some white squares (possibly zero) black so that the squares painted black are connected. Find the minimum number of squares he needs to repaint to achieve his objective.

Here, the squares painted black are said to be connected when, for every pair of squares (S,T)(S,T) painted black, there are a positive integer KK and a sequence of KK squares X=(x1,x2,,xK)X=(x_1,x_2,\ldots,x_K) painted black such that x1=Sx_1=S, xK=Tx_K=T, and xix_i and xi+1x_{i+1} share a side for every 1iK11\leq i\leq K-1. It can be proved that, under the constraints of the problem, there is always a way for Takahashi to achieve his objective.

Constraints

  • 1N1001 \leq N \leq 100
  • 1M71\leq M \leq 7
  • NN and MM are integers.
  • SiS_i is a string of length MM consisting of # and ..
  • The given grid has at least one square painted black.

Input

The input is given from Standard Input in the following format:

NN MM

S1S_1

S2S_2

\vdots

SNS_N

Output

Print the minimum number of squares that Takahashi needs to repaint for the squares painted black to be connected.

3 5
...#.
.#...
....#
3

The initial grid looks as follows, where (i,j)(i,j) denotes the square at the ii-th row from the top and jj-th column from the left.

Assume that Takahashi repaints three squares (2,3),(2,4),(3,4)(2,3),(2,4),(3,4) (shown red in the figure below) black.

Then, we have the following squares painted black, including the ones painted black from the beginning. These squares are connected.

It is impossible to repaint two or fewer squares black so that the squares painted black are connected, so the answer is 33. Note that the squares painted white do not have to be connected.

3 3
###
###
###
0

All squares might be painted black from the beginning.

10 1
.
#
.
.
.
.
.
.
#
.
6