题目链接:http://poj.org/problem?id=1753
解题思路:
首先看到每个棋子2种状态,就想起了位存储的方法,而棋盘只有16格。正好可以用一个int变量来存储这16个状态。剩下的就是广搜了。暴力枚举的话也只需要65535次即可。在枚举状态时,如果某个状态出现过,则进入死循环,无法翻转到全黑或全白(如果能的话,第一次就找到了,就不会再回到这个状态了)。
PS:这道题竟然是OJ题目表初级里面的第一题,我擦,坑了多少人????枚举+BFS+位存储,这让新手咋入门。。。。。我想拿这道题练下手,结果悲剧了半天才过。。。
代码如下:
#include <iostream>
#include <queue>
using namespace std;
const int MAX_STATE = 65536;
const int ALL_BLACK = 65535;
const int ALL_WHITE = 0;
const int SIZE = 4;
int convert(char c)
{
if(c == 'b')
return 1;
else
return 0;
}
int FlipPiece(int state_id, int pos)
{
state_id ^= (1 << pos); //自身取反
//up
if(pos >= 4)
state_id ^= (1 << (pos-4));
//down
if(pos + 4 < SIZE*SIZE)
state_id ^= (1 << (pos+4));
//left
if(pos % 4 != 0)
state_id ^= (1<<(pos-1));
//right
if(pos % 4 != 3)
state_id ^= (1 << (pos+1));
return state_id;
}
int main()
{
int current_state_id = 0;
int state[MAX_STATE];
queue<int> search_queue;
memset(state, -1, sizeof(state));
char color;
for(int i = 0; i < SIZE*SIZE; i++)
{
cin >> color;
current_state_id += convert(color) << i;
}
if(current_state_id == ALL_WHITE || current_state_id == ALL_BLACK)
{
printf("0\n");
return 0;
}
state[current_state_id] = 0;
search_queue.push(current_state_id);
int next_state_id;
while(!search_queue.empty())
{
current_state_id = search_queue.front();
search_queue.pop();
for(int i = 0; i < SIZE*SIZE; ++i)
{
next_state_id = FlipPiece(current_state_id, i);
if(next_state_id == ALL_WHITE || next_state_id == ALL_BLACK) //满足题意
{
cout << state[current_state_id] + 1 << endl;
return 0;
}
if(state[next_state_id] == -1 ) //没有重复出现过
{
state[next_state_id] = state[current_state_id] + 1;
search_queue.push(next_state_id);
}
}
}
cout << "Impossible" << endl;
return 0;
}