第一行的每个格子按或不按两种选择 m列则有2^m种情况 通过dfs确定
每一个元素都只能通过按下下一行的同列格子来改变 最后看一下第n行是否全为0即可
using namespace std;
int e[20][20],tt[20][20],pre[20][20];
int n,m,ans;
void flip(int mat[][20],int x,int y);
void dfs(int step);
int calculate();
int main()
{
int i,j;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf("%d",&e[i][j]);
}
}
memset(tt,0,sizeof(tt));
ans=N;
dfs(1);
if(ans==N) printf("IMPOSSIBLE\n");
else
{
for(i=1;i<=n;i++)
{
for(j=1;j<=m-1;j++)
{
printf("%d ",pre[i][j]);
}
printf("%d\n",pre[i][j]);
}
}
}
return 0;
}
void flip(int mat[][20],int x,int y)
{
mat[x][y]^=1;
mat[x][y-1]^=1;
mat[x-1][y]^=1;
mat[x][y+1]^=1;
mat[x+1][y]^=1;
return;
}
void dfs(int step)
{
int tem,i,j;
if(step==m+1)
{
tem=calculate();
if(tem!=-1&&tem<ans)
{
memcpy(pre,tt,sizeof(tt));
ans=tem;
}
return;
}
dfs(step+1);
tt[1][step]=1;
flip(e,1,step);
dfs(step+1);
tt[1][step]=0;
flip(e,1,step);
return;
}
int calculate()
{
int t[20][20];
int i,j,cnt;
memcpy(t,e,sizeof(e));
cnt=0;
for(i=2;i<=n;i++)
{
for(j=1;j<=m;j++)
{
tt[i][j]=0;
}
}
for(i=1;i<=n-1;i++)
{
for(j=1;j<=m;j++)
{
if(t[i][j]==1)
{
tt[i+1][j]=1;
flip(t,i+1,j);
cnt++;
}
}
}
for(j=1;j<=m;j++)
{
cnt+=tt[1][j];
}
for(j=1;j<=m;j++)
{
if(t[n][j]==1)
{
return -1;
}
}
return cnt;
}