Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M × N grid (1 ≤ M ≤ 15; 1 ≤ N ≤ 15) of square tiles, each of which is colored black on one side and white on the other side.
As one would guess, when a single white tile is flipped, it changes to black; when a single black tile is flipped, it changes to white. The cows are rewarded when they flip the tiles so that each tile has the white side face up. However, the cows have rather large hooves and when they try to flip a certain tile, they also flip all the adjacent tiles (tiles that share a full edge with the flipped tile). Since the flips are tiring, the cows want to minimize the number of flips they have to make.
Help the cows determine the minimum number of flips required, and the locations to flip to achieve that minimum. If there are multiple ways to achieve the task with the minimum amount of flips, return the one with the least lexicographical ordering in the output when considered as a string. If the task is impossible, print one line with the word "IMPOSSIBLE".
思路:如果第一行确定了,后面就确定了。所以直接枚举第一行所有的可能情况,复杂度
#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <string>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
int n,m;
int a[20][20], res[20][20], minPath[20][20], aux[20][20];
int minStep=999999;
void flip(int i,int j)
{
a[i][j]=1-a[i][j];
if(i-1>=0) a[i-1][j]=1-a[i-1][j];
if(j-1>=0) a[i][j-1]=1-a[i][j-1];
if(i+1<n) a[i+1][j]=1-a[i+1][j];
if(j+1<m) a[i][j+1]=1-a[i][j+1];
}
void check(int cnt)
{
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
aux[i][j]=a[i][j];
int flag=1;
for(int i=1;i<n;i++)
{
for(int j=0;j<m;j++)
{
// before check, clear
res[i][j]=0;
if(a[i-1][j]==1)
{
// must flip
flip(i,j);
res[i][j]=1;
cnt++;
}
}
// check previous row
for(int j=0;j<m;j++)
{
if(a[i-1][j]!=0)
{
flag=0;
break;
}
}
if(flag==0) break;
}
// check last row
for(int j=0;j<m;j++)
{
if(a[n-1][j]!=0)
{
flag=0;
break;
}
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
a[i][j]=aux[i][j];
if(flag==1 && cnt<minStep)
{
minStep=cnt;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
minPath[i][j]=res[i][j];
}
}
void dfs(int col,int cnt)
{
if(col==m)
{
check(cnt);
return;
}
dfs(col+1,cnt);
flip(0,col);
res[0][col]=1;
dfs(col+1,cnt+1);
flip(0,col);
res[0][col]=0;
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>a[i][j];
memset(res,0,sizeof(res));
dfs(0,0);
if(minStep==999999)
cout<<"IMPOSSIBLE"<<endl;
else
{
//cout<<minStep<<endl;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cout<<minPath[i][j]<<(j==m-1?"\n":" ");
}
return 0;
}