Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=1372

骑士环游 BFS

我的代码
 1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 using namespace std;
5 const int dx[8]={-1,1,2,2,1,-1,-2,-2};
6 const int dy[8]={2,2,1,-1,-2,-2,-1,1};
7 int dis[10][10],vis[10][10];
8 queue<int> q;
9 int bfs(int sx,int sy,int ex,int ey)
10 {
11 if (sx==ex && sy==ey) return 0;
12 while (!q.empty()) q.pop();
13 int x,y,nx,ny;
14 int u=sx*9+sy;
15 vis[sx][sy]=1; dis[sx][sy]=0;
16 q.push(u);
17 while (!q.empty())
18 {
19 u=q.front(); q.pop();
20 x=u/9; y=u%9;
21 for (int d=0;d<8;d++)
22 {
23 nx=x+dx[d]; ny=y+dy[d];
24 if (nx<1 || nx>8 || ny<1 || ny>8 || vis[nx][ny]) continue;
25 vis[nx][ny]=1; dis[nx][ny]=dis[x][y]+1;
26 if (nx==ex && ny==ey) return dis[nx][ny];
27 q.push(nx*9+ny);
28 }
29 }
30 return 0;
31 }
32 int main()
33 {
34 char s1[5],s2[5];
35 int sx,sy,ex,ey;
36 while (scanf("%s%s",s1,s2)!=EOF)
37 {
38 memset(dis,0,sizeof(dis));
39 memset(vis,0,sizeof(vis));
40 sx=s1[0]-96; sy=s1[1]-'0';
41 ex=s2[0]-96; ey=s2[1]-'0';
42 printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs(sx,sy,ex,ey));
43 }
44 }

 

posted on 2011-12-16 19:45  Qiuqiqiu  阅读(168)  评论(0编辑  收藏  举报