Description
Input
The input consists of 4 lines with 4 characters “w” or “b” each that denote game field position.
Output
Write to the output file a single integer number - the minimum number of rounds needed to achieve the goal of the game from the given position. If the goal is initially achieved, then write 0. If it’s impossible to achieve the goal, then write the word “Impossible” (without quotes).
Sample Input
bwwb
bbwb
bwwb
bwww
Sample Output
4
思路
本来是搜索的题目,本菜鸡用的枚举QAQ
- 基本上的思路和熄灯问题一样,枚举出对第一行开关进行操作的16种情况,再对下面的各行进行操作。最后判断最后一排是否符合要求。
- 最大的感觉是这道题的代码量比较大,错误不好找,心累。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
char m[5][5], t[5][5];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
int ans = INF, cnt;
void turn(int x, int y)
{
if (m[x][y] == 'b')
m[x][y] = 'w';
else
m[x][y] = 'b';
}
void filp(int x, int y)
{
turn(x, y);
for (int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < 4 && ny >= 0 && ny < 4)
turn(nx, ny);
}
}
bool judge(char c)//判断最后一行是否全为颜色
{
bool flag = true;
for (int i = 0; i < 4; i++)
if (m[3][i] != c)
flag = false;
return flag;
}
//全翻转成某种颜色时
void op(char c)
{
for (int i = 0; i < 1 << 4; i++){
cnt = 0;
for (int j = 0; j < 4; j++)//第一行
if ((i >> j) & 1){
filp(0, j);
cnt++;
}
for (int j = 1; j < 4; j++)//后面三行
for (int k = 0; k < 4; k++){
if (m[j - 1][k] == 'b'){
filp(j, k);
cnt++;
}
}
if (judge('w'))
ans = min(cnt, ans);
memcpy(m, t, sizeof t);//恢复成初始状态
}
}
int main(void)
{
for (int i = 0; i < 4; i++)
cin >> m[i];
memcpy(t, m, sizeof m);//保存初始状态
//全翻转成白色时
op('w');
//全翻转成黑色时
op('b');
if (ans == INF)
cout << "Impossible" << endl;
else
cout << ans << endl;
return 0;
}