POJ 1753
#include<iostream>
#include<bitset>
#include<queue>
using namespace std;
queue<bitset<16>> state; //record the state of each situation
bool flag[65536] = { false }; <span style="white-space:pre"> </span>//in case repeated search
int step[65536] ;
void Initialize()
{
cout << "Please input a 4*4 rectangle while 'b' represents 'black' "
<< "and 'w' represents 'white':\n";
char c;
int i = 0, j = 0;
bitset<16> temp;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
cin >> c;
if ('b' == c)
temp.set(4 * i + j);
}
}
state.push(temp);
flag[temp.to_ulong()] = true;
}
bitset<16> Flip(bitset<16> piece, int i)
{
if (i % 4 != 0) //not in the first column
piece.reset(i - 1);
if ((i + 1) % 4 != 0) //not in the fourth column
piece.reset(i + 1);
if (i > 3) //not in the first row
piece.reset(i - 4);
if (i < 12) //not in the fourth row
piece.reset(i + 4);
return piece;
}
bool breadFirstSearch()
{
while (!state.empty())
{
bitset<16> firstState = state.front();
state.pop(); //queue.pop() do not return the value of the first item!
for (int i = 0; i < 16; i++)
{
bitset<16> temp = Flip(firstState, i);
if (firstState.none() || (firstState.count() == 16))
{
cout << step[firstState.to_ulong()];
return true;
}
else if(!flag[temp.to_ulong()])
{
state.push(temp);
flag[temp.to_ulong()] = true;
step[temp.to_ulong()] = step[firstState.to_ulong()] + 1;
}
}
}
return false;
}
int main()
{
Initialize();
if (!breadFirstSearch())
cout << "Impossible!";
return 0;
}
最后:
1. 2^16=65536 ,如果设置的数组大小为65535,那么
输入:
bbbb
bbbb
bbbb
bbbb
输出则是 溢出的
2. bitset<> 会比^ | &方便使用
3.广度优先遍历使用队列作为基本的数据结构,深度优先算法依赖于栈(在递归中显示或隐士地使用栈)
4.做ACM..不是为了成为ACMer,只是想对数据结构和算法有一个应用实践