poj 1753 骑士游历问题 广度优先搜索 + 位压缩

//======================================================================
//
//>		  Author		:		flowertree
//>		  About			:		poj 1753
//>		  Time			:		2015.12.28
//>		  Algorithm		:		BFS + 位压缩 黑白棋问题
//						:		含有大量位运算
//						
//=======================================================================

#include <iostream>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;

#define MAX 65536

struct node
{
	int num;
	int steps;
};

char map[6][6];
bool flag[MAX];
int s;		//开始状态要压缩成的数
int bit[17] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 0};
int Move[5][2] = {1, 0, -1, 0, 0, 1, 0, -1, 0, 0};		//棋子变的格子

void Init()
{
	s = 0;
	memset(flag, false, sizeof(flag));
	for(int i = 1; i <= 4; i++)		//开始状态压缩成一个数
	{
		cin >> map[i] + 1;
		for(int j = 1; j <= 4; j++)
		{
			if(map[i][j] == 'w')
			{
				s = s | bit[(4 * (4 - i) + (4 - j))];
			}
		}
	}
}

bool judge(int n)		//黑为0,白为1
{
	if(n == 65535)
		return true;
	int temp1 = n & 0x0000000F;
	int temp2 = n & 0x000000F0;
	int temp3 = n & 0x00000F00;
	int temp4 = n & 0x0000F000;
	if((temp1 == 0) && (temp2 == 0) && (temp3 == 0) && (temp4 == 0))
		return true;
	else
		return false;
}

int bfs()		//广度优先搜索
{
	if(judge(s))
		return 0;
	queue<node> q;
	node n;
	n.num = s;
	n.steps = 0;
	q.push(n);
	while(!q.empty())
	{
		node t = q.front();
		q.pop();
		for(int i = 1; i <= 4; i++)
		{
			for(int j = 1; j <= 4; j++)
			{
				int temp = t.num;
				for(int k = 0; k < 5; k++)
				{
					int tempx = i + Move[k][0];
					int tempy = j + Move[k][1];
					if((tempx < 1) || (tempx > 4) || (tempy < 1) || (tempy > 4))
						continue;
					temp = temp ^ bit[(4 * (4 - tempx) + (4 - tempy))];
				}
				if(judge(temp))
					return t.steps + 1;
				if(!flag[temp])
				{
					flag[temp] = true;
					node l;
					l.num = temp;
					l.steps = t.steps + 1;
					q.push(l);
				}
			}
		}
	}
	return -1;
}

int main()
{
	Init();	
	int temp = bfs();
	if(temp == -1)
		cout << "Impossible" << endl;
	else
		cout << temp << endl;
	system("pause");
	return 0;
}

你可能感兴趣的:(位运算,算法,动态规划,poj)