题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1072
一看到题目,感觉题目有点长,不怎么想读,匆匆读一遍,表示没怎么看懂,结果又仔细读了一遍,才知道规则就是“马走日”。
显然用bfs就AC了
#include<iostream> #include<queue> using namespace std; bool vis[9][9]; int sx,sy,ex,ey; char sta[3]; char End[3]; struct node { int x,y; int step; }; queue<node>q; bool check(int x,int y) { if(x<1||y<1||x>8||y>8) return false; return true; } void out(int n) { printf("To get from %s to %s takes %d knight moves.\n",sta,End,n); } void bfs() { int div[8][2]={{-1,-2},{-1,2},{-2,-1},{-2,1},{1,2},{1,-2},{2,1},{2,-1}}; while(!q.empty()) q.pop(); node s; s.x=sx; s.y=sy; s.step=0; vis[sx][sy]=true; q.push(s); while(!q.empty()) { s=q.front(); q.pop(); if(s.x==ex&&s.y==ey) { out(s.step); break; } node e; for(int i=0;i<8;i++) { e.step=s.step+1; e.x=s.x+div[i][0]; e.y=s.y+div[i][1]; if(check(e.x,e.y)&&vis[e.x][e.y]==false) { q.push(e); vis[s.x][s.y]=true; } } } } int main() { //freopen("test.txt","r",stdin); while(scanf("%s%s",sta,End)!=EOF) { memset(vis,false,sizeof(vis)); sx=sta[0]-'a'+1; sy=sta[1]-'0'; ex=End[0]-'a'+1; ey=End[1]-'0'; bfs(); } return 0; }