题目:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1363
#include<cstdio>
#include<cstring>
#include<queue>
#include<set>
using namespace std;
struct State
{
short step,x,y;
char map[5][5];
};
struct cmp
{
bool operator () (State a,State b) const
{
return memcmp(a.map,b.map,25)<0;
}
};
char final[5][5]={'1','1','1','1','1','0','1','1','1','1','0','0',' ','1','1','0','0','0','0','1','0','0','0','0','0'};
set<State,cmp> vis;
int try_to_insert(State s)
{
if(vis.count(s)) return 0;
vis.insert(s);
return 1;
}
void solve(State &head)
{
if(memcmp(head.map,final,sizeof(final))==0)
{
printf("Solvable in 0 move(s).\n");
return;
}
queue<State> q;
q.push(head);
while(!q.empty())
{
int i;
short dir[8][2]={-1,-2,1,-2,-2,-1,2,-1,-1,2,1,2,-2,1,2,1};
State cur;
cur=q.front();
q.pop();
if(cur.step>=11)
{
printf("Unsolvable in less than 11 move(s).\n");
return;
}
if(memcmp(cur.map,final,sizeof(final))==0)
{
printf("Solvable in %d move(s).\n",cur.step);
return;
}
for(i=0;i<8;i++)
{
State next=cur;
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
if(next.x<0||next.x>4||next.y<0||next.y>5) continue;
char t=next.map[next.x][next.y];
next.map[next.x][next.y]=next.map[cur.x][cur.y];
next.map[cur.x][cur.y]=t;
next.step++;
if(try_to_insert(next))
q.push(next);
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
int i,j,N;
State head;
scanf("%d",&N);
getchar();
while(N--)
{
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
head.map[i][j]=getchar();
if(head.map[i][j]==' ')
{
head.x=i;
head.y=j;
}
}
getchar();
}
head.step=0;
vis.clear();
solve(head);
}
return 0;
}