#C4013. Minimum Paint Operations for Uniform Grid

    ID: 47505 Type: Default 1000ms 256MiB

Minimum Paint Operations for Uniform Grid

Minimum Paint Operations for Uniform Grid

You are given a grid of dimensions \( m \times n \) where each cell contains an integer representing its color. Two cells are considered adjacent if they share a common side. In one operation, you can repaint an entire connected region (i.e. a maximal set of adjacent cells having the same color) to any color. The goal is to make the grid uniform, meaning that no two adjacent cells have different colors.

Task: Compute the minimum number of operations required such that the grid becomes uniformly colored. Note that this is equivalent to merging all connected components into one. Thus, the answer is \(\text{number of connected components} - 1\).

Example 1:

Input:
3 3
1 2 2
3 3 3
4 4 4
Output:
3

Example 2:

Input:
2 2
1 1
1 2
Output:
1

inputFormat

The first line of input contains two integers \( m \) and \( n \) representing the number of rows and columns of the grid respectively.

The next \( m \) lines each contain \( n \) integers, where each integer represents the color of the cell.

outputFormat

Output a single integer denoting the minimum number of painting operations required so that no two adjacent cells have different colors.

## sample
3 3
1 2 2
3 3 3
4 4 4
3