zoukankan      html  css  js  c++  java
  • C语言编程练习57:马的移动

    题目描述

    小明很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
    给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
    现请你编程解决这个问题。

    提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。

    输入

    输入包含多组测试数据。每组输入由两个方格组成,每个方格包含一个小写字母(a~h),表示棋盘的列号,和一个整数(1~8),表示棋盘的行号。

    输出

    对于每组输入,输出一行“To get from xx to yy takes n knight moves.”。

    样例输入 Copy

    e2 e4
    a1 b2
    b2 c3
    a1 h8
    a1 h7
    h8 a1
    b1 c3
    f6 f6

    样例输出 Copy

    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.

    思路:宽度优先搜索,每一步有8种选择。
    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <set>
    
    using namespace std;
    int c[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,-1},{-2,1}};//下一步的8种选择
    int visit[9][9];//记录是否走过
    int x1,y1,x2,y2;//开始和结束的坐标
    int minstep;
    char s1[5],s2[5];
    
    void bfs(int a,int b,int cnt)
    {
        int n,m;
        if(a==x2&&b==y2)
        {
            if(minstep>cnt)
            minstep=cnt;
            return;
        }
        if(cnt>minstep)
        {
            return;
        }
        for(int i=0;i<8;i++)
        {
            n=a+c[i][0];
            m=b+c[i][1];
            if(n>8||n<1||m<1||m>8)
            {
                continue;
            }
            if(visit[n][m]==0)
            {
                visit[n][m]=1;
                bfs(n,m,cnt+1);
                visit[n][m]=0;
            }
        }
    }
    int main()
    {
        while(scanf("%s %s",s1,s2)!=EOF)
        {
            minstep=9999;
            x1=s1[0]-'a'+1;
            x2=s2[0]-'a'+1;
            y1=s1[1]-'0';
            y2=s2[1]-'0';
            memset(visit,0,sizeof(visit));
            visit[x1][y1]=1;
            bfs(x1,y1,0);
            printf("To get from %s to %s takes %d knight moves.
    ",s1,s2,minstep);
        }
        
        return 0;
    }
    
     
  • 相关阅读:
    linux-指令
    rabbitmq启动
    [浪峰前端开发]JS获取当前时间戳的方法
    [浪峰JQuery开发]jquery最有意思的IFrame类似应用--值得深入研究
    [浪峰分享]移动电商:不是渠道拓展,而是一次重新创业
    [浪峰分享]App必死 Web永生 看Web的前世今生 必会卷土重来
    [浪峰分享]推荐一些不错的计算机书籍
    [浪峰转载]Jquery取得iframe中元素的几种方法
    [浪峰分享] 如何管理一个远程团队
    [浪峰分享] 博客园博客导航固顶--简单实用的css代码
  • 原文地址:https://www.cnblogs.com/FantasticDoubleFish/p/14433110.html
Copyright © 2011-2022 走看看