This can be tested as follows:
Take the first column of the target matrix. All other columns should be either the same as that first column, or should be its opposite (flipped). If, and only when, this is the case then the target matrix can be reached through flips of rows/columns from the initial matrix having all 1 values.
You can also do the test with rows of course, but it is enough to perform it with either rows or columns.
Which flips to perform?
You can also see which flips you can perform to reach a target matrix in case the above test is positive:
In the first row of the target matrix, identify the cells with value 0: those are the columns you need to flip in the initial matrix.
In the first column of the target matrix, identify the cells with a value different from the value in the top-left corner of the target matrix (so this already excludes the first value): those are the rows you need to flip in the initial matrix.
The order in which the flips are performed is not important. Obviously, this gives just one solution. There can be more than one in general.
Implementation
Here is a simple JavaScript snippet that performs the verification and provides a list of columns and rows to swap if possible:
function getFlips(matrix) {
// Verification
for (let i = 1; i < matrix.length; i++) {
let flip = matrix[i][0] ^ matrix[0][0]; // XOR operation
for (let j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] ^ flip != matrix[0][j]) return false; // Not possible
}
}
// If we get here, it is possible: determine which rows/columns to flip
let flips = { rows: [], columns: [] };
for (let j = 0; j < matrix[0].length; j++) {
if (matrix[0][j] == 0) flips.columns.push(j+1);
}
for (let i = 1; i < matrix.length; i++) {
if (matrix[i][0] != matrix[0][0]) flips.rows.push(i+1);
}
return flips;
}
// I/O management
inp.oninput = function () {
// Convert input to matrix of numbers
let matrix = inp.value.split('\n').map(row => Array.from(row, Number));
// Perform algorithm
let flips = getFlips(matrix);
// Output the result in human readable format
out.textContent = flips
? 'Number(s) of the column(s) to flip: '
+ (flips.columns.length ? flips.columns : 'none') + '\n' +
'Number(s) of the row(s) to flip: '
+ (flips.rows.length ? flips.rows : 'none')
: 'Not possible';
};
inp.oninput();
Enter the values of the matrix:<br>
<textarea id="inp" rows="4" cols="4">101
010
101</textarea><br>
Solution:
<pre id="out"></pre>