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

题目大意:

有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;
}




你可能感兴趣的:((pojstep1.1)1753(dfs+枚举))