POJ 1753/BFS:翻转棋

黑白棋翻转

4X4的棋盘有2^16种状态,如果状态值为0或65535则算法结束

第一层:初始状态

第二层:初始状态翻0、初始状态翻1、初始状态翻……初始状态翻15

第三层:  ………………………….

如果该状态值未访问过,则入队列

#include <iostream>
#define MAX_STATE 65535
#define ALL_BLACK 65535
#define ALL_WHITE 0
#define WIDTH 4
#define HEIGTH 4
#define SIZE_OF_BOARD WIDTH*HEIGTH
#include <queue>

using namespace std;

int flip(int current,int pos){
	current ^=1<<pos;
	if(pos>=WIDTH)current ^=1<<(pos-WIDTH);
	if(pos+WIDTH<SIZE_OF_BOARD)current ^=1<<(pos+WIDTH);
	if(pos%WIDTH!=0)current ^=1<<(pos-1);
	if(pos%WIDTH!=WIDTH-1)current ^=1<<(pos+1);
	return current;
}
int main(int argc, char* argv[])
{
	
	
	int step[MAX_STATE];
	int current_state = 0,next_state;
//	for(int i=0;i<HEIGTH;i++)
//	{
//		for(int j=0;j<WIDTH;j++)
//			current_state += (getchar()=='b')<<(i*WIDTH+j);
//		getchar();	
//		
//	}
	//debug("%d",8^2);
	char c;
	for(int i=0;i<SIZE_OF_BOARD;i++)
	{
		cin>>c;
		current_state += (c=='b')<<(i);
		//debug("%d",c);
	}
	if(current_state==ALL_WHITE||ALL_BLACK==current_state){
		printf("0\n");
		return 0;
	}
	memset(step,-1,MAX_STATE);
	queue<int> q;
	q.push(current_state);
	step[current_state]=0;
	//debug("%d",current_state);
	while(!q.empty()){
		current_state = q.front();
		q.pop();
		//debug("%d",current_state);
		for(int i=0;i<SIZE_OF_BOARD;i++)
		{
			next_state = flip(current_state,i);
			
			if(next_state==ALL_WHITE||next_state==ALL_BLACK){
				printf("%d\n",step[current_state]+1);
				return 0;
			}
			if(-1==step[next_state]){
				step[next_state] = step[current_state]+1;
				q.push(next_state);
			}
		}
		
	}
	printf("Impossible\n");
	//debug("%d",current_state);
	
	
	return 0;
}
posted on 2011-06-05 21:12  yangyh  阅读(372)  评论(0编辑  收藏  举报