Harvesting a Farm
Time limit1sMemory limit128 MB
Given a grid of crops 1 and 2 with no 2x2 checkerboard, find the minimum number of cutter changes (including the first attachment) to harvest every cell, moving freely only on matching or empty cells.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Greedy, Implementation
- Solved
- No attempts yet
Problem
A farmer owns a rectangular farm. The farm is divided into equal-sized square cells, and each cell has one of two crops planted in it: wheat or corn. Wheat is denoted by the digit 1 and corn by the digit 2.
Through many years of experience, the farmer has found that, to improve crop quality, no adjacent block of cells may form either of the following two "crossing" patterns. (Every farm given in the input always satisfies this rule.)
Crossing pattern 1
Crossing pattern 2
The farmer has a combine for harvesting. To harvest a given crop, a special cutter matching that crop must be attached to the combine. While no cutter is attached, and also while a cutter is being replaced, the combine may be moved freely to any cell of the farm without harvesting anything. However, once a cutter is attached, the combine may move only over cells planted with the crop matching that cutter, or over cells that are already empty (harvested earlier).
Because replacing a cutter is tedious, the farmer wants to minimize the number of cutter replacements needed to harvest the entire farm. Write a program that computes this minimum number of cutter replacements.
Input
The input consists of multiple test cases. The first line of each test case contains two integers and , the number of rows and columns of the farm (). Each of the next lines contains characters from the set , giving the crop planted in the corresponding cell. The input ends with a line containing 0 0.
Output
For each test case, print on its own line the minimum number of times the farmer must replace the combine's cutter. Attaching a cutter to the combine for the first time also counts as one replacement.