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".
Input
Lines 2..
M+1: Line
i+1 describes the colors (left to right) of row i of the grid with
N space-separated integers which are 1 for black and 0 for white
Output
M: Each line contains
N space-separated integers, each specifying how many times to flip that particular location.
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 嗯,这个题我觉得很好啊,是dfs入门的经典题型啊,关键是翻转一次会影响周围的状态,除了用dfs以外,也可以用枚举(开关问题),
这里我只使用了dfs(枚举还不会orz)。
dfs搜索的话,肯定不是按一条一条路径来搜,我们可以dfs第一行的所有翻转情况,然后从第一行的情况可以递推出下面行的状态,
下面行中只要上行对应列有黑色就把这个位置翻转,因为会影响周围,所有上面行也会翻转。
至于字典序,因为一开始dfs第一行的时候是直接搜到底的,所以后面的dfs情况都是从最右边开始向左翻转的,如果有相同的最小值,那么记录下的一定是最右边的情况。
注意路径的回溯
#include<bits/stdc++.h> using namespace std; int m,n;
int ans; int maps[][];
int vis[][];
int vistmp[][];
int way[][] = {,,,,,,,-,-,};
void inif()
{
memset(vis,,sizeof(vis));
memset(vistmp,,sizeof(vistmp));
for(int i=;i<=m;i++)
{
for(int j=;j<=n;j++)
{
scanf("%d",&maps[i][j]);
}
}
}
void flip(int x,int y)
{
vistmp[x][y] ^= ;
for(int i=;i<;i++)
{
int xx = x+way[i][];
int yy = y+way[i][];
if(<xx && xx<=m && yy> && yy <=n)
{
maps[xx][yy] ^= ;
}
}
}
void solve(int k,int cnt)
{
if(cnt >= ans)return;
if(k == m)
{
int i;
for(i=;i<=n;i++)
if(maps[m][i])break;
if(i <= n)return;
ans = cnt;
memcpy(vis,vistmp,sizeof(vistmp));
return;
}
for(int i=;i<=n;i++)
{
if(maps[k][i])
{
flip(k+,i);
cnt++;
}
}
solve(k+,cnt);
for(int i=;i<=n;i++)
{
if(vistmp[k+][i])flip(k+,i);
}
return;
}
void dfs(int k,int cnt)
{
if(cnt >= ans)return;
else if(k == n+)
{
solve(,cnt);
return;
}
else
{
dfs(k+,cnt);
flip(,k);
dfs(k+,cnt+);
flip(,k);
}
}
int main()
{
while(~scanf("%d%d",&m,&n))
{
ans = 0x3f3f3f3f;
inif();
dfs(,);
if(ans == 0x3f3f3f3f)printf("IMPOSSIBLE\n");
else
{
for(int i=;i<=m;i++)
{
for(int j=;j<=n;j++)
{
if(j != )
printf(" %d",vis[i][j]);
else
printf("%d",vis[i][j]);
}
puts("");
}
}
}
}