比POJ 2965 简单一点不用输出路径,直接上代码了
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int map[6][6];
char a[6][6];
int flag;
int ans;
int dx[] = {0,1,-1,0};
int dy[] = {1,0,0,-1};
bool check()
{
int i, j;
for(i = 1;i <= 4;i++){
for(j = 1;j <= 4;j++){
if(map[i][j] != map[1][1])
return false;
}
}
return true;
}
void change(int x, int y)
{
map[x][y] = !map[x][y];
for(int i = 0;i < 4;i++){
map[x+dx[i]][y+dy[i]] = !map[x+dx[i]][y+dy[i]];
}
}
void dfs(int x, int y, int cur)
{
if(cur == ans){
flag = check();
return ;
}
if(flag||x == 5)
return;
change(x,y);
if(y < 4){
dfs(x,y+1,cur+1);
}else {
dfs(x+1,1,cur+1);
}
change(x,y);
if(y < 4){
dfs(x,y+1,cur);
}else{
dfs(x+1,1,cur);
}
}
int main()
{
int i, j;
for(i = 0;i < 4;i++){
cin >> a[i];
}
for(i =1;i <= 4;i++){
for(j = 1;j <= 4;j++){
if(a[i-1][j-1] == 'b')
map[i][j] = 1;
else if(a[i-1][j-1] =='w'){
map[i][j] =0;
}
}
}
for(ans = 0;ans <= 16;ans++){
dfs(1,1,0);
if(flag) break;
}
if(flag){
printf("%d\n", ans);
}else {
printf("Impossible\n");
}
return 0;
}