5. Colored Balls 2D
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given an $$$n \times m$$$ rectangular grid of colored balls, where each ball can be one of three colors. In a single step, you may swap any two balls. Determine the minimum number of steps required to arrange the balls such that the grid is partitioned into single-colored rectangles — one rectangle for each color present.

Input

The first line of the input contains two integers $$$n$$$ and $$$m$$$. The following $$$n$$$ lines each contain $$$m$$$ integers (1, 2, or 3), representing the colors of the balls.

Output

Output a single integer: the minimum number of steps required. If no solution exists, output -1.

Scoring

Subtask 1 (up to 20 points): $$$1 \le n, m \le 10$$$; the balls can only be of color 1 or 2.

Subtask 2 (up to 20 points): $$$1 \le n, m \le 1000$$$; the balls can only be of color 1 or 2.

Subtask 3 (up to 24 points): $$$1 \le n, m \le 10$$$; the balls can be of color 1, 2, or 3.

Subtask 4 (up to 36 points): $$$1 \le n, m \le 1000$$$; the balls can be of color 1, 2, or 3.

Examples
Input
3 4
1 2 1 1
2 1 1 3
3 3 3 1
Output
2
Input
2 2
1 1
1 1
Output
0
Input
2 3
1 1 1
1 1 2
Output
-1
Note

In the first example, it is sufficient to swap the first two balls in the first row and the last two balls in the last column.

A note for those using Python: You can read a sequence of space-separated integers as follows:

c = [int(x) for x in input().split()]