Description:
There are m * n (m <= 100, n <=100) coins on the desktop forming a m row n column coin matrix. Every coin either face upward, or face backward, represented by 0 or 1.
Rules of the game are:
(1) every time, you are allowed to inverse one row of coins.
(2) every time, you are allowed to swap two columns.
Object:
from initial matrix -> target matrix
Input:
1. k the count of test caese
2. m n the count of rows and columns
3. the numbers of the inital matrix and the target matrix
Output
the least steps from initial matrix to target matrix, if it is not possible to transfer from initial to target, output -1.
sample intput
2
4 3
1 0 1
0 0 0
1 1 0
1 0 1
1 0 1
1 1 1
0 1 1
1 0 1
4 3
1 0 1
0 0 0
1 0 0
1 1 1
1 1 0
1 1 1
0 1 1
1 0 1
sample output
2
-1
I have coded one solution: mysolution.cc, which enumerate all posibilities and which is correct but it is too slow, could you provide a correct but fast solution.
Thanks.
The rows always stay in the same place, so if row
rstarts withkones, it will always have eitherkones orcolumns - k.count_of_ones(initial,row) == count_of_ones(target,row), if yes, fine, else check ifcount_of_ones(initial,row) = columns - count_of_ones(target,row), if so, flip row, else output-1. As @maniek pointed out, it’s not so easy when exactly half of the columns contain ones. Such rows would have to be treated in step 2 to try and form the required columns.-1, otherwise try to find a permutation of columns that transforms working to target (any columns identical between working and target have to be kept fixed). If not possible, output-1, otherwise find minimum number of swaps necessary to achieve that permutation.