简而言之就是给定MN矩阵,里边部分是1部分是0,每次翻转会把当前块和上下左右四块同时翻转(0变1,1变0),求最少翻转次数以使矩阵中所有数都是0(相同步数按输出矩阵字典序输出)。
输出的也是一个MN矩阵,其中每个数字代表当前块被翻转的次数(因为翻转两次就会变为原来的情况所以输出矩阵中应该只有0和1)
Sample Input
4 4
1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1
Sample Output
0 0 0 0
1 0 0 1
1 0 0 1
0 0 0 0
思路: 题目很难思考,因为每翻转一个块都会影响周围四个(看了大佬们的题解才会做我太菜了) 解决办法是通过二进制压缩遍历第一行,之后以下每行的操作目的就是为了将上一行全部归零(如果当前行的上一行没能通过当前行的操作变为全0,那么它再也没法变为全0 了) 所以通过遍历第一行的所有翻转情况,之后每行根据上一行的1的位置进行翻转,最后判断最后一行是否都为0就可以了
按 0000 -> 0001 -> 0010… 的顺序进行遍历即可保证按字典序输出 每次遍历后记录步数并与最小步数比较并更新,无需记录结果矩阵,记录下得到最优值的首行操作,最后输出的时候再模拟一下就好
oj里记得include </cstdio/>,只用iostream会compile error的
代码如下: (习惯于写松散的代码了…看起来会很长)
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int grid[16][16],storage[16][16],way[16];
int method,steps;
int M,N;
void flip(int i,int j) // 翻转函数,对上下左右中翻转
{
storage[i][j] = !storage[i][j];
if(i-1>0)
storage[i-1][j] = !storage[i-1][j];
if(j-1>0)
storage[i][j-1] = !storage[i][j-1];
if(i+1<=M)
storage[i+1][j] = !storage[i+1][j];
if(j+1<=N)
storage[i][j+1] = !storage[i][j+1];
}
void search(int currWay)
{
for(int i = 0;i<N;i++) //位运算重要
{
way[N-i] = (currWay >> i)&1; //提取当前遍历方式存到数组中
}
int tempstep = 0;
for(int i=1;i<=M;i++)
{
for(int j=1;j<=N;j++)
{
storage[i][j]=grid[i][j]; // 复制一遍原数组,避免在原数组基础上进行修改
}
}
for(int i=1;i<=M;i++)
{
for(int j=1;j<=N;j++)
{
if(i==1) { // 第一行,根据传入的遍历方式来翻转
if (way[j] == 1)
{
flip(i, j);
tempstep++;
}
}
else { // 之后,根据上一行的结果翻转
if (storage[i - 1][j] == 1) {
flip(i, j);
tempstep++;
}
}
}
}
bool flag = true;
for(int j=1;j<=N;j++) // 判断最后一行是否全0
{
if(storage[M][j]==1)
{
flag = false;
break;
}
}
if(flag && steps>tempstep) // 获得了更小的步数,更新步数和当前方法
{
steps = tempstep;
method = currWay;
}
}
void printAns(int currWay) // 打印结果函数,基本上是复制了上边的函数,重新模拟跑一遍输出
{
for(int i = 0;i<N;i++)
{
way[N-i] = (currWay >> i)&1;
}
for(int i=1;i<=M;i++)
{
for(int j=1;j<=N;j++)
{
storage[i][j]=grid[i][j];
}
}
for(int i=1;i<=M;i++)
{
for(int j=1;j<=N;j++)
{
if(i==1) {
if (way[j] == 1)
{
flip(i, j);
cout << "1 ";
} else
cout << "0 ";
}
else {
if (storage[i - 1][j] == 1) {
flip(i, j);
cout << "1 ";
} else
{
cout << "0 ";
}
}
}
cout << endl;
}
}
int main() {
while(scanf("%d %d",&M,&N)!=EOF)
{
steps=pow(2,30);
for(int i=1;i<=M;i++)
{
for(int j=1;j<=N;j++)
{
scanf("%d",&grid[i][j]);
}
}
for(int i=0; i < (1 << N); i++) // 二进制压缩位运算※
{
search(i);
}
if(steps!=pow(2,30))
printAns(method);
else
cout <<"IMPOSSIBLE"<<endl;
}
return 0;
}