您的位置:首页 > 其它

POJ 1753 棋盘反转(位运算+BFS)

2013-09-30 03:16 344 查看
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

#define ROW 1
#define COL 2
#define MAX 6
#define ENDSTATE ((1<<16)-1)

const int dir[5][3] = { {0,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1} };

int arr[MAX][MAX];
int chess[MAX][MAX];
int change[17];
bool visit[(1 << 16)];

int initVal = 0;

struct Node{

Node():state( 0 ),step( 0 ){};
Node(int sa,int se):state( sa ),step( se ){};

int state;
int step;

};

void getChange(){

int index = 1;
memset( arr, 0, sizeof( arr ) );

for( int i = 1;i <= 4; ++i ){
for( int j = 1;j <= 4; ++j ){

int temp = 0;

for( int k = 1;k <= 4; ++k ){
arr[i + dir[k][ROW]][j + dir[k][COL]] = 1;
}

arr[i][j] = 1;

for( int m = 1;m <= 4; ++m ){
for( int n = 1;n <= 4; ++n ){
temp <<= 1;
if( arr[m]
==1 )
temp += 1;
}
}

change[index] = temp;
index++;
memset( arr, 0, sizeof( arr ) );
}
}
}

int BFS(){

queue<Node>Q;
Node cur( initVal, 0 );
visit[initVal] = true;

Q.push( cur );

while( !Q.empty() ){

Node temp = Q.front();
Q.pop();

if( temp.state == 0 || temp.state == ENDSTATE )
return temp.step;

for( int i = 1; i <= 16; ++i ){

Node nextNode;
int val = temp.state ^ change[i];

if( visit[val] == true )
continue;

nextNode.state = val;
nextNode.step = temp.step + 1;
visit[val] =true;

Q.push( nextNode );
}
}

return -1;
}

int main(){

getChange();

memset( visit, false, sizeof( visit ) );
bool label = false;
int base;

for( int i = 1; i <= 4; ++i ){
for( int j = 1; j <= 4; ++j ){

initVal <<= 1;
char c;
cin >> c;

if( c == 'b' )
initVal += 1;
}
}

int step = BFS();

if( step == -1 )
cout << "Impossible" << endl;
else
cout << step << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: