This page is still under construction.

Parts of this page are still being built. What you see may change.

Cow Beauty Pageant

Time limit1sMemory limit128 MB

Summary
Given a grid with exactly three connected X-spots, find the fewest empty cells to paint so the three spots merge into one connected region.
Level

Hard8 of 10

Topics
BFS, Graph, Brute force
Solved
No attempts yet

Problem

Hearing that the latest fashion trend was cows with three spots on their hides, Farmer John bought an entire herd of three-spot cows. Unfortunately, fashion changes quickly, and the hottest look now is a cow with only one spot!

Farmer John wants to make his herd more fashionable by painting each cow so that its three spots merge into one. A cow's hide is given as an N×MN \times M grid of characters like this:

................
..XXXX....XXX...
...XXXX....XX...
.XXXX......XXX..
........XXXXX...
..XXX....XXX....

Here each 'X' is part of a spot. Two 'X's belong to the same spot if they are vertically or horizontally adjacent (diagonal adjacency does not count), so the figure above has exactly three spots. Every cow in the herd has exactly three spots.

Farmer John wants to use as little paint as possible to merge the three spots into one. In the example above he can do it by painting only four extra cells with 'X' (the new cells are marked with '*' below to make them easier to see):

................
..XXXX....XXX...
...XXXX*...XX...
.XXXX..**..XXX..
...*....XXXXX...
..XXX....XXX....

Please determine the minimum number of new 'X's that must be painted to merge the three spots into one single spot.

Input

  • Line 1: Two space-separated integers NN and MM (1≤N,M≤501 \le N, M \le 50).
  • Lines 2 through N+1N+1: Each contains a length-MM string of 'X' and '.' describing one row of the cow-hide pattern.

Output

  • Line 1: The minimum number of new 'X's that must be added to the pattern to obtain one single spot.

Hint

The example pattern has three separate spots, and painting four new 'X' cells is enough to join the three spots into one.

Examples3

  1. Example 1

    Input
    6 16
    ................
    ..XXXX....XXX...
    ...XXXX....XX...
    .XXXX......XXX..
    ........XXXXX...
    ..XXX....XXX....
    
    Expected output
    4
    
  2. Example 2

    Input
    1 5
    X.X.X
    
    Expected output
    2
    
  3. Example 3

    Input
    3 5
    X...X
    .....
    ..X..
    
    Expected output
    4