Under construction

Still being built. Things may change

Harvesting a Farm

Time limit1sMemory limit128 MB

Summary
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 n×mn \times m 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 2×22 \times 2 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

12
21

Crossing pattern 2

21
12

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 nn and mm, the number of rows and columns of the farm (1≤n×m≤1051 \le n \times m \le 10^5). Each of the next nn lines contains mm characters from the set {1,2}\{1, 2\}, 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.

Examples1

  1. Example 1

    Input
    2 3
    112
    211
    4 4
    1212
    2211
    1112
    1222
    0 0
    
    Expected output
    2
    3