There are N× Ncards, which form an N× Nmatrix. The cards can be placed upwards or downwards. Now Acer is going to do some operations so that all the cards are placed upwards after the operations. In each operation, Acer can flip over exactly an M× Msub-matrix of cards. Acer wants to know the minimum number of operations to achieve his goal.
Input
The first line contains two integers, N and M (0 < M ≤ N ≤ 1000).
Each of the next N lines contains N integers. If the integer is 1, the corresponding card is placed upwards initially; otherwise it is placed downwards initially.
Output
Output an integer, which indicate the minimum number of operations. If there is no solution, output -1.
Sample Input
4 2 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0
Sample Output
5
#include<iostream>
int a[1001][1001];
int n,m;
int cnt=0;
void dfs(int x){
if (x+m>n){
for(int i=x;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j]==0){
cnt=-1;
return;
}
}
}
return;
}
for(int i=0;i<n;i++){
if(a[x][i]!=1){
if(i+m>n){
cnt=-1;
return;
}
cnt++;
for(int k=x;k<x+m;k++){
for(int j=i;j<i+m;j++){
a[k][j]=!a[k][j];
}
}
}
}
dfs(x+1);
}
using namespace std;
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>a[i][j];
}
}
dfs(0);
cout<<cnt;
return 0;
}