Binary Grid

Time limit: 1s Memory limit: 256MB Input: Output:

You are given a grid AA consisting of NN rows and MM columns, containing only of 00s and 11s.

You can do the following operations on AA:

  • Select a row ii (0iN10 \leq i \leq N - 1) and invert it (i.e. flip every value in that row, such that each 00 becomes a 11 and each 11 becomes a 00).
  • Select a column jj (0jM10 \leq j \leq M - 1) and invert it.

A binary grid is beautiful if there are no three consecutive equal values in the same row or in the same column. More formally, there is no ii, jj (0iN10 \leq i \leq N - 1, 0jM30 \leq j \leq M - 3) such that Ai,j=Ai,j+1=Ai,j+2A_{i,j} = A_{i,j} + 1 = A_{i,j} + 2, and there is no ii, jj (0iN3,0jM10 \leq i \leq N - 3, 0 \leq j \leq M - 1) such that Ai,j=Ai+1,j=Ai+2,jA_{i,j} = A_{i+1,j} = A_{i+2,j}.

Task

Your task is to decide whether it is possible to make a given grid beautiful, and if so, then report the minimum number of operations to do it.

Input data

The first line of the input file contains a single integer TT, the number of testcases. TT testcases follow, each preceded by an empty line.

Each testcase consists of:

  • a line containing two space-separated integers NN and MM.
  • NN lines, the (i+1)(i+1)-th of which consisting of string AiA_i consisting of 00s and 11s representing row ii of the grid.

Output data

The output file must contain TT lines, each consisting of a single integer, the answers of the testcases. If it is possible to make a grid beautiful, then the answer to the testcase is the minimum number of operations to do so, otherwise, if it is impossible, then the answer is 1-1.

Constraints and clarifications

  • 1T1001 \leq T \leq 100
  • 1N2 0001 \leq N \leq 2 \ 000
  • 1M2 0001 \leq M \leq 2 \ 000
  • Ai,jA_{i,j} is either 00 or 11 for each 0iN10 \leq i \leq N - 1 and 0jM10 \leq j \leq M - 1.
  • The sum of NN over all testcases is at most 2 0002 \ 000.
  • The sum of MM over all testcases is at most 2 0002 \ 000.
# Points Constraints
1 0 Examples
2 9 N10N \leq 10 and M10M \leq 10. The sum of NN and the sum of MM over all testcases do not exceed 1010.
3 12 N=1N=1
4 20 N10N \leq 10. The sum of NN over all testcases does not exceed 1010.
5 59 No additional constraints

Example

stdin

3

4 4
0001
1110
1010
1000

3 3
011
101
110

5 5
11111
10001
11011
10001
11111

stdout

3
0
-1

Explanation

Explanation of the first sample:

In the first testcase, a possible way to make the grid beautiful using 33 operations is as follows:

  • Invert column 00.
  • Invert row 22.
  • Invert column 11.

In the second testcase, the grid is already beautiful, thus no operations are needed.

In the third testcase, it is impossible to make the grid beautiful using the mentioned operations.

Log in or sign up to be able to send submissions!