UVA 439 BFS 骑士的移动
#include<iostream> #include<cstdio> #include<string> #include<string.h> #include<math.h> #include<queue> #include<map> #include<algorithm> using namespace std; int dx,dy; struct node{ int step; int x; int y; friend bool operator <(node a,node b){ return a.step>b.step; } }; int dir[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{2,-1},{1,-2}}; priority_queue<node> q; int bfs(){ int s,d; while(!q.empty()){ node temp=q.top(); q.pop(); if(dx==temp.x&&dy==temp.y){return temp.step;} for(int i=0;i<8;i++){ s=temp.x+dir[i][0]; d=temp.y+dir[i][1]; if(s>0&&s<9&&d>0&&d<9){ node next; next.x=s; next.y=d; next.step=temp.step+1; q.push(next); } } } return 0; } int main(){ int a,b,ss; char f,g; while(cin>>f>>b>>g>>dy){ a=f-'a'+1; dx=g-'a'+1; while(!q.empty()) q.pop(); node n; n.x=a; n.y=b; n.step=0; q.push(n); ss=bfs(); printf("To get from %c%d to %c%d takes %d knight moves.\n",f,b,g,dy,ss); } return 0; }