Cow Beauty Pageant
InterviewTime limit1sMemory limit128 MB
Given a grid with exactly two connected X regions, find the minimum number of dots to paint so the two regions become one.
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 grid of characters ():
................
..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 and .
- Lines 2 to : each line is a string of length made of
Xand.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....