The algorithm is based on counting. A solvable board has each row/column either the same as the first row/column or exactly cell-by-cell reversed color of the first row/column.

In the loop we count for **rs** and **cs**, the number of rows/columns being the same as the first row/column, and **rm** and **cm**, the number of misplaced rows/columns in the view of the first row/column. If any row/column is found to be neither the same nor reversed color then returns -1 immediately.

Then, for even number **n** there are two final forms of the first row/column. We compute the minimum swaps of the two cases. For odd number **n** there is only one final form of the board so we compute the swaps based on the fact that whether the first row/column is in the less or the greater half.

```
int movesToChessboard(vector<vector<int>>& b) {
int n = b.size();
int rs = 0, cs = 0, rm = 0, cm = 0;
for (int i = 0; i < n; i++) {
bool rf = b[0][0] == b[i][0], cf = b[0][0] == b[0][i];
rs += rf, cs += cf;
rm += rf ^ !(i & 1), cm += cf ^ !(i & 1);
for (int j = 0; j < n; j++)
if ((b[0][j] == b[i][j]) ^ rf || (b[j][0] == b[j][i]) ^ cf)
return -1;
}
if (n % 2 == 0) {
if (rs == n / 2 && cs == n / 2)
return min(rm, n - rm) / 2 + min(cm, n - cm) / 2;
return -1;
}
int res = 0;
if (rs == n / 2)
res += (n - rm) / 2;
else if (rs == n / 2 + 1)
res += rm / 2;
else
return -1;
if (cs == n / 2)
res += (n - cm) / 2;
else if (cs == n / 2 + 1)
res += cm / 2;
else
return -1;
return res;
}
```