uva439 Knight Moves

广搜 模板题

#include<bits/stdc++.h>
using namespace std;
queue<pair<int,int> >que;
int sx,sy,mx,my;
int nxt[8][2]={{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{1,-2},{2,-1}},v[10][10];
int main()
{
   char a[10],b[10];
   while(~scanf("%s %s",a,b)){
        //cout<<a<<b<<endl;
        sx=a[1]-'0';sy=a[0]-'a'+1;
        mx=b[1]-'0';my=b[0]-'a'+1;
        while(!que.empty()) que.pop();
        memset(v,0,sizeof(v));
        que.push(make_pair(sx,sy));
        v[sx][sy]=1;
        while(!que.empty()){
            pair<int,int> now=que.front();
            que.pop();
            if(now.first==mx&&now.second==my){
               printf("To get from %s to %s takes %d knight moves.\n",a,b,v[mx][my]-1);
               break;
            }
            for(int i=0;i<8;i++){
                 int nx=now.first+nxt[i][0];
                 int ny=now.second+nxt[i][1];
                 if(!v[nx][ny]&&nx>=1&&ny>=1&&nx<=8&&ny<=8){
                     v[nx][ny]=v[now.first][now.second]+1;
                     que.push(make_pair(nx,ny));
                 }
            }
        }
   }
}

你可能感兴趣的:(uva439 Knight Moves)