(pojstep1.1)1753(dfs+枚举)

探讨一个4x4的棋盘翻转问题,通过递归深度优先搜索算法求解最少翻转次数使棋盘统一颜色。文章提供了一种有效的解决方案,并详细解释了其实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:

有4*4的正方形,每个格子要么是黑色,要么是白色,当把一个格子的颜色改变(黑->白或者白->黑)时,其周围上下左右(如果存在的话)的格子的颜色也被反转,问至少反转几个格子可以使4*4的正方形变为纯白或者纯黑?



代码如下:

/*
 * 1753_1.cpp
 *
 *  Created on: 2013年9月13日
 *      Author: Administrator
 */


#include <iostream>
#include <cstdio>
using namespace std;


/**
 * chess[][] :棋子的翻转情况
 * flag : 判断是否是清一色
 * step :已经进行的步数
 * r[] :方向向量, 行移动的方向
 * c[] :方向向量, 列移动的方向
 */
bool chess[6][6] = {false};//不要写成5,因为这里没对特定边界值进行处理。利用的只有中心的4x4
bool flag;
int step;
int r[5] = {1,-1,0,0,0};
int c[5] = {0,0,1,-1,0};

/**
 * 判断所有棋子是否同色
 */
bool judge_all(){
	int i,j;
	for(i = 1 ; i < 5 ; ++i){
		for(j = 1 ; j < 5 ; ++j){
			if(chess[i][j] != chess[1][1]){
				return false;
			}
		}
	}

	return true;
}

/**
 * 翻转其中的一枚棋子,机器周围的棋子
 */
void flip(int row,int col){
	int i;
	for(i = 0 ; i < 5 ; ++i){
		chess[row + r[i]][col + c[i]] = !chess[row + r[i]][col + c[i]];
	}

}


void dfs(int row,int col , int deep){
	if(deep == step){
		flag = judge_all();
		return ;
	}

	if(flag || row == 5){
		return ;
	}

	flip(row,col);//翻棋
	if(col < 4){
		dfs(row,col+1,deep+1);
	}else{
		dfs(row+1,1,deep+1);
	}

	flip(row,col);//不符合则翻回来
	if(col < 4){
		dfs(row,col+1,deep);
	}else{
		dfs(row+1,1,deep);
	}

	return ;
}

int main(){
	int i,j;
	char temp;

	flag = false;
	step = 0;

	for(i = 1 ; i < 5 ; ++i){
		for(j = 1 ; j < 5 ; ++j){
			cin >> temp;
			if(temp == 'b'){
				chess[i][j] = true;
			}
		}
	}

	/**
	 *  对每一步产生的可能性进行枚举
	 *  至于为什么是16,考虑到4x4=16格,而每一格只有黑白两种情况,则全部的可能性为2^16
	 */
	for(step = 0 ; step <=16 ; ++step){
		dfs(1,1,0);
		if(flag){
			break;
		}
	}

	if(flag){
		cout<<step<<endl;
	}else{
		printf("Impossible\n");
	}
	
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅气的东哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值