深度优先搜索暴力搜一遍。
dfs带了两个参数,一个是当前的深度(0是第一次),一个是当前节点已经翻的次数。
#include <iostream>
using namespace std;
bool maze[4][4];//棋盘
int ans = -1;//答案
bool isend()//棋子是否都一样
{
bool m = maze[0][0];
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
if(m != maze[i][j])
return false;
return true;
}
//翻一个棋子
void fan(int x, int y)
{
maze[x][y] = !maze[x][y];
if(x - 1 >= 0)
maze[x - 1][y] = !maze[x - 1][y];
if(x + 1 <= 3)
maze[x + 1][y] = !maze[x + 1][y];
if(y - 1 >= 0)
maze[x][y - 1] = !maze[x][y - 1];
if(y + 1 <= 3)
maze[x][y + 1] = !maze[x][y + 1];
}
//深度优先搜索,q是深度
void dfs(int q, int num)
{ //坐标
int x = q / 4, y = q % 4;
if(isend()){
if(num < ans || ans == -1 )
ans = num;
}
if(q > 15)
return;
//不翻的左子树
dfs(q + 1, num);
fan(x, y);
num++;
//翻了的右子树
dfs(q + 1, num);
//回溯时翻回来
fan(x, y);
num--;
}
int main()
{
char c;
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++){
cin >> c;
if(c != '\n')
maze[i][j] = (c == 'b')?true:false;
}
//从-1开始才能从0分叉,从0会从1分叉
dfs(-1, 0);
if(ans == -1)
cout << "Impossible\n";
else{
cout << ans << endl;
}
return 0;
}