A - Flip Game

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

  1. 基本上的思路和熄灯问题一样,枚举出对第一行开关进行操作的16种情况,再对下面的各行进行操作。最后判断最后一排是否符合要求。
  2. 最大的感觉是这道题的代码量比较大,错误不好找,心累。
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值