先放上我参考的题解:http://blog.csdn.net/lyy289065406/article/details/6642595
看第一眼感觉和poj 3279题差不多,只是目标不一样。poj 3279是要求全部白面向上,直接用循环枚举比较方便。这个题目是要求同一个颜色的面向上,朝上的面就有两种颜色了,如果像3279那个题一样作的话,感觉就要麻烦了一点。于是就看了上边链接大神的题解,恍然大悟阿。
#include <iostream>
using namespace std;
bool board[6][6] = {false};//从[1][1]开始,就不需要处理边界了
bool flag = false;
int step;
//判断是否全都一种颜色
int judge()
{
for(int i = 1; i <= 4; ++i)
for(int j = 1; j <= 4; ++j)
if(board[i][j] != board[1][1])
return false;
return true;
}
//翻转
void flip(int row, int col)
{
board[row][col] = !board[row][col];
board[row-1][col] = !board[row-1][col];
board[row][col-1] = !board[row][col-1];
board[row][col+1] = !board[row][col+1];
board[row+1][col] = !board[row+1][col];
}
void dfs(int row, int col, int dep)
{
if(dep == step)
{
flag = judge();
return;
}
if(flag || row == 5) return;
//翻转当前坐标的碟子
flip(row,col);
if(col < 4)
dfs(row,col+1,dep+1);
else
dfs(row+1,1,dep+1);
//将当前坐标碟子翻回原样,从旁边的碟子开始继续翻
flip(row,col);
if(col < 4)
dfs(row,col+1,dep);
else
dfs(row+1,1,dep);
}
int main()
{
char ch;
for(int i = 1; i <= 4; ++i)
for(int j = 1; j <= 4; ++j)
{
cin >> ch;
if(ch == 'b')
board[i][j] = true;
}
for(step = 0; step <= 16; ++step)
{
dfs(1,1,0);
if(flag) break;
}
if(flag)
cout << step << endl;
else
cout << "Impossible" << endl;
return 0;
}