这是一道典型的BFS模板题,解题的关键是要知道国际象棋的马是走日字型
下面贴出代码:
#include<iostream> #include<queue> #include<cstdio> #include<cstring> using namespace std; int vis[10][10]; int dir[8][2]={1,2,2,1,-1,2,-2,1,-2,-1,-1,-2,2,-1,1,-2}; struct node { int x; int y; int step; }; int bfs(int x1,int y1,int x2,int y2) { queue<node>q; int i; node a,b; a.x=x1; a.y=y1; a.step=0; vis[a.x][a.y]==1; q.push(a); while(!q.empty()) { a=q.front(); q.pop(); if(a.x==x2&&a.y==y2)return a.step; for(i=0;i<8;i++) { b.x=a.x+dir[i][0]; b.y=a.y+dir[i][1]; if(b.x>=1&&b.x<=8&&b.y>=1&&b.y<=8&&!vis[b.x][b.y]) { b.step=a.step+1; vis[b.x][b.y]=1; q.push(b); } } } return -1; } int main() { int x1,x3,y1,y2,ans; char c1,c2,c3;//一开始这三个字符型变量和整形变量放在一起定义了,弄得代码样例一直通不过。。。。这种低级错误,,真是智商拙计啊.. while(scanf("%c%d%c%c%d",&c1,&x1,&c2,&c3,&x3)!=EOF) { getchar(); memset(vis,0,sizeof(vis)); y1=c1-'a'+1;//巧妙之处把含有字母的起点和重点直接化成数字坐标 y2=c3-'a'+1; ans=bfs(x1,y1,x3,y2); if(c1==c3&&x1==x3)printf("To get from %c%d to %c%d takes 0 knight moves.\n",c1,x1,c3,x3); else printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,x1,c3,x3,ans); } return 0; }