zoukankan      html  css  js  c++  java
  • 【题解】Knight Moves-C++

    题目
    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},{2,1},{-2,1},{2,-1},{-2,-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,sy,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 }
    个人博客地址: www.moyujiang.com 或 moyujiang.top
  • 相关阅读:
    【C++】深度探索C++对象模型读书笔记--关于对象(Object Lessons)
    【操作系统】调度算法
    【vim】vim常用命令
    【linux】linux的数据流重定向
    以太网帧,IP,TCP,UDP首部结构
    IPv4编址及子网划分
    【计算机网络】计算机网络模型
    【计算机网络】NAT:网络地址转换
    【设计模式】C++中的单例模式
    (转)linux查找技巧: find grep xargs
  • 原文地址:https://www.cnblogs.com/moyujiang/p/11213507.html
Copyright © 2011-2022 走看看