题目链接:http://poj.org/problem?id=2697
只是状态的储存问题,可以把棋盘拉成长度为16的字符串,用map来储存就可以。
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <queue>
#include <map>
#include <string>
using namespace std;
const int dx[8] = {-1,-1,-1,0,0,1,1,1};
const int dy[8] = {-1,0,1,-1,1,-1,0,1};
map<string,bool> f;
struct node
{
string state;
int step;
char col;
};
node st,ed;
queue<node> Q;
void init()
{
st.state = "";
for (int i=0; i<4; i++)
{
char str[5];
scanf("%s",str);
getchar();
for (int j=0; j<4; j++)
st.state = st.state + str[j];
}
st.step = 0;
ed.state = "";
for (int i=0; i<4; i++)
{
char str[5];
scanf("%s",str);
getchar();
for (int j=0; j<4; j++)
ed.state = ed.state + str[j];
}
}
bool next(node& now, int pos, int j)
{
int nowi = pos/4;
int nowj = pos - nowi*4;
int newi = nowi+dx[j], newj = nowj+dy[j];
int newpos = newi*4+newj;
int cnt = 0;
while (newi>=0 && newi<=3 && newj>=0 && newj<=3 && now.state[newpos]=='*')
{
cnt++;
now.state[newpos] = now.state[pos];
now.state[pos] = '*';
newi = newi+dx[j]; newj = newj+dy[j];
pos = newpos;
newpos = newi*4+newj;
}
now.step++;
return cnt;
}
int BFS()
{
while (!Q.empty()) Q.pop();
f.clear();
st.col = 'b';
Q.push(st);
st.col = 'w';
Q.push(st);
f[st.state] = 1;
while (!Q.empty())
{
node now = Q.front();
node tmp = now;
Q.pop();
for (int i=0; i<16; i++)
if (now.state[i] != '*' && now.state[i] != now.col)
for (int j=0; j<8; j++)
{
if (!next(now,i,j))
{
now = tmp;
continue;
}
node New = now;
New.col = now.col == 'b' ? 'w' : 'b';
now = tmp;
if (New.state == ed.state)
return New.step;
if (f[New.state] == 0)
{
f[New.state] = 1;
Q.push(New);
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d",&t);
getchar();
while (t > 0)
{
t--;
init();
printf("%d\n",BFS());
}
return 0;
}