水题,裸的bfs,基本没有要注意的
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> #define INF 1E9 using namespace std; const int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,1,2,-1}; int vis[9][9]; struct node { int x,y; }; queue<node> q; char aim[3],stt[3]; node st,am,now,temp; int i; int main() { while(~scanf("%s%s",stt,aim)) { memset(vis,0,sizeof(vis)); while(!q.empty())q.pop(); st.x=stt[0]-'a';st.y=stt[1]-'1'; am.x=aim[0]-'a';am.y=aim[1]-'1'; vis[st.x][st.y]=1; q.push(st); while(!q.empty()&&!vis[am.x][am.y]) { now=q.front();q.pop(); for(i=0;i<8;i++) { temp.x=now.x+dir[i][0]; temp.y=now.y+dir[i][1]; if(temp.x<0||temp.x>7||temp.y<0||temp.y>7||vis[temp.x][temp.y])continue; vis[temp.x][temp.y]=vis[now.x][now.y]+1; q.push(temp); } } printf("To get from %s to %s takes %d knight moves.\n",stt,aim,vis[am.x][am.y]-1); } }