Problem 423
Shortest Bridge
Medium · 20 pts · Matrix, Breadth-First Search, Depth-First Search
Problem
A grid contains exactly two islands. An island is a group of land cells ('1') connected up, down, left or right; everything else is water ('0'). You may turn water cells into land. Find the smallest number of water cells you must convert so that the two islands become connected into one. Mark one island, then run a breadth-first search outwards from all of its cells at once; the first time the search reaches the other island, the distance travelled is the answer.
Input
First line: R and C. Next R lines: C characters, each '0' or '1'. There are exactly two islands.
Output
Print the minimum number of cells to convert.
Constraints
2 <= R, C <= 100
Example input
3 3 010 000 001
Example output
2
Explanation
In 010 / 000 / 001, converting two water cells, for example the middle cell and the cell to its right, joins the two islands. One cell is not enough, so the answer is 2.