题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372
题目描述:
在一个棋盘中,给你两个点的坐标,同时,你有八种走法,当然题目没明确说,但是这种棋盘就是这种规则。
求:从第一个点都第二个点的最少步数;
注意:
1.因为坐标是字母加数字的形式,注意下输入格式
2.如果用scanf读取输入,那么别忘了加!=EOF,否则会报 Output limit error 错误
3. 如果输入坐标的时候全部按字符格式输入的,在转成数字的时候,字母减掉 'a' ,那么数字要减掉 '1' ,这样横纵坐标的范围才能控制在 0-7
1 //cin字母加数字输入 2 #include3 #include 4 #include 5 #include 6 using namespace std; 7 8 char c1,c2; 9 int sxx,exx;10 int sx,sy,ex,ey;11 int go[8][2] = { 1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2};12 bool vis[10][10];13 struct node14 {15 int x,y;16 int count;17 };18 19 bool check(node s)20 {21 if(s.x>=0&&s.x<8&&s.y>=0&&s.y<8)22 return 1;23 else24 return 0;25 }26 void bfs()27 {28 queue Q;29 node now,nex;30 now.x = sx;now.y = sy;31 now.count = 0;32 vis[now.x][now.y] = 1;33 Q.push(now);34 while(!Q.empty())35 {36 now = Q.front();37 Q.pop();38 if(now.x==ex&&now.y==ey)39 {40 printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,sxx,c2,exx,now.count);41 return ;42 }43 for(int i=0;i<8;i++)44 {45 nex.x = now.x + go[i][0];46 nex.y = now.y + go[i][1];47 if(check(nex)&&!vis[nex.x][nex.y])48 {49 vis[nex.x][nex.y] = 1;50 nex.count = now.count + 1;51 Q.push(nex);52 }53 }54 }55 cout<<"0"< >c1>>sxx>>c2>>exx)61 {62 sy = c1 - 'a';63 sx = sxx - 1;64 ey = c2 - 'a';65 ex = exx - 1;66 memset(vis,0,sizeof(vis));67 bfs();68 }69 return 0;70 }
1 //scanf字符数组输入 2 #include3 #include 4 #include 5 #include 6 using namespace std; 7 8 char s1[3],s2[3]; 9 int sx,sy,ex,ey;10 int go[8][2] = { 1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2};11 bool vis[10][10];12 struct node13 {14 int x,y;15 int count;16 };17 18 bool check(node s)19 {20 if(s.x>=0&&s.x<8&&s.y>=0&&s.y<8)21 return 1;22 else23 return 0;24 }25 void bfs()26 {27 queue Q;28 node now,nex;29 now.x = sx;now.y = sy;30 now.count = 0;31 vis[now.x][now.y] = 1;32 Q.push(now);33 while(!Q.empty())34 {35 now = Q.front();36 Q.pop();37 if(now.x==ex&&now.y==ey)38 {39 printf("To get from %s to %s takes %d knight moves.\n",s1,s2,now.count);40 return ;41 }42 for(int i=0;i<8;i++)43 {44 nex.x = now.x + go[i][0];45 nex.y = now.y + go[i][1];46 if(check(nex)&&!vis[nex.x][nex.y])47 {48 vis[nex.x][nex.y] = 1;49 nex.count = now.count + 1;50 Q.push(nex);51 }52 }53 }54 cout<<"0"<