加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

【题解】Knight Moves-C++

发布时间:2020-12-16 07:18:39 所属栏目:百科 来源:网络整理
导读:题目 Description 在一个8*8的棋盘上,一只中国象棋中的马要从一个点跳到另一个点。问最少需要多少步。 Input 整个测试组由多组数据组成,请做到文件底结束。 对于每组数据,前两个坐标代表出发点,后两个代表结束点。注意坐标第一位为a至h中某个字母,第二

题目
Description
在一个8*8的棋盘上,一只中国象棋中的马要从一个点跳到另一个点。问最少需要多少步。
Input
整个测试组由多组数据组成,请做到文件底结束。
对于每组数据,前两个坐标代表出发点,后两个代表结束点。注意坐标第一位为a至h中某个字母,第二位为1到8某个数字。
Output
对于每个测试请输出"To get from xx to yy takes n knight moves.".
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.

思路
广搜,每次输入字符串先存起来,转成两对坐标,按照正常的搜索去做就行了,然后唯一不同的是dir数组要按照马的走法来打,具体看下面代码是怎么写的,其他的坑点不多,就是要注意输出格式中空格的位置以及个数(真心劝告!!!)

代码

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 string o1,o2;
 4 int sx,sy,ex,ey,cnt;
 5 int dir[8][2]={{1,2},{1,-2},{-1,{2,1},{-2,-1},-1}};
 6 struct node
 7 {
 8     int x,y,t;
 9     node(){};
10     node(int xx,int yy,int tt)
11     {
12         x=xx,y=yy,t=tt;
13     }
14 };
15 bool vis[10][10];
16 bool in(int x,int y)
17 {
18     return 1<=x&&x<=8&&1<=y&&y<=8;
19 }
20 void bfs()
21 {
22     queue<node> q;
23     q.push(node(sx,0));
24     vis[sx][sy]=0;
25     while(!q.empty())
26     {
27         node now=q.front();
28         q.pop();
29         if(now.x==ex&&now.y==ey)
30         {
31             cout<<"To get from "<<o1<<" to "<<o2<<" takes "<<now.t<<" knight moves."<<endl;
32             return;
33         }
34         for(int i=0;i<8;i++)
35         {
36             int tx=now.x+dir[i][0],ty=now.y+dir[i][1];
37             if(in(tx,ty)&&!vis[tx][ty])
38             {
39                 q.push(node(tx,ty,now.t+1));
40                 vis[tx][ty]=1;
41             }
42         }
43     }
44     cout<<"f**k"<<endl;
45     return;
46 }
47 int main()
48 {
49     while(cin>>o1>>o2)
50     {
51         memset(vis,0,sizeof(vis));
52         sx=o1[0]-a+1,sy=o1[1]-0;
53         ex=o2[0]-a+1,ey=o2[1]-0;
54         bfs();
55     }
56     return 0;
57 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读