This page is still under construction.

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

Cow Beauty Pageant

Interview

Time limit1sMemory limit128 MB

Summary
Given a grid with exactly two connected X regions, find the minimum number of dots to paint so the two regions become one.
Level

Medium5 of 10

Topics
BFS, Graph
Solved
No attempts yet

Problem

Farmer John heard that the newest fashion trend is cows with two spots on their hides, so he bought a whole herd of two-spot cows. Unfortunately, fashion changes fast, and now the hottest look is cows with only one spot!

To make his herd fashionable again, FJ wants to paint each cow so that its two spots merge into a single spot. A cow's hide is given as an N×MN \times M grid of characters (1≤N,M≤501 \le N, M \le 50):

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

Each X is part of a spot. Two Xs belong to the same spot if they are vertically or horizontally adjacent (diagonal adjacency does not count), so the hide above has exactly two spots. Every cow in the herd has exactly two spots.

FJ wants to use as little paint as possible to merge the two spots into one. In the example above, he can do it by painting just three extra cells with X (marked with * below to make them easy to see):

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

Help FJ find the minimum number of new Xs he must paint so that the two spots become one single spot.

Input

  • Line 1: two space-separated integers NN and MM.
  • Lines 2 to N+1N+1: each line is a string of length MM made of X and . describing one row of the hide.

Output

  • One line: the minimum number of new Xs that must be added so that the pattern becomes a single spot.

Hint

The input pattern shows a hide with two distinct spots, labeled 1 and 2 below:

................
..1111....222...
...1111....22...
.1111......222..
........22222...
.........222....

Three new Xs are enough to join the two spots into one:

................
..1111....222...
...1111X...22...
.1111..XX..222..
........22222...
.........222....

Examples3

  1. Example 1

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

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

    Input
    1 3
    X.X
    
    Expected output
    1