BFS 搜索 Problem 1015 Knight Moves "马走日"之最少步数

Problem ID:1015 Knight Moves


简单题意:给出一个8*8的棋盘,一个起始点,一个目的点,从起始点开始,按照“马走日”规则行走。求到达目的点的最少步数。


解题思路形成过程:用BFS的方式进行遍历,每个点可以往8个方向前进。

            如果前进需要满足2个条件:①:此点在棋盘内;

                             ②:此点在之前没有遍历过。

            利用数组储存地图以及行走过的点。


感想:注意字符类型的输入处理。

    注意数组不要超出范围(debug了好一会儿)。


代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int dir[8][2]={{-1,-2},{-2,-1},{-1,2},{-2,1},{1,-2},{2,-1},{1,2},{2,1}};//八个方向
int cmap[8][8];
char a1,b1;
int  a2,b2;
int bfs(int r,int c)
{
    queue<int>q;
    q.push(r);
    q.push(c);
    q.push(0);
    while(!q.empty())
    {
        int nr=q.front();
        q.pop();
        int nc=q.front();
        q.pop();
        int nct=q.front();
        q.pop();
        for(int i=0;i<8;++i){
            int tr=nr+dir[i][0];
            int tc=nc+dir[i][1];
            int tct=nct+1;
            if(tr>=0&&tr<8&&tc>=0&&tc<8){
                if(cmap[tr][tc]==2)     //此条件语句不能单独列出,必须在if(tr>=0&&tr<8&&tc>=0&&tc<8)内,否则会出错!
                  return tct;
                if(cmap[tr][tc]==0){
                    q.push(tr);
                    q.push(tc);
                    q.push(tct);
                    cmap[tr][tc]=1;
                }
            }
        }
    }
}
int main()
{
    //freopen("1.txt","r",stdin);
    while(scanf("%c",&a1)!=EOF)
    {
        scanf("%d",&a2);//注意字符类型的输入处理。
        getchar();
        scanf("%c%d",&b1,&b2);
        getchar();
        memset(cmap,0,sizeof(cmap));
        int r1=a2-1;
        int c1=a1-'a';
        int r2=b2-1;
        int c2=b1-'a';
        cmap[r1][c1]=1;
        cmap[r2][c2]=2;
        if(r1==r2&&c1==c2){
            printf("To get from %c%d to %c%d takes 0 knight moves.\n",a1,a2,b1,b2);
            continue;
        }
        int cnt=bfs(r1,c1);
        printf("To get from %c%d to %c%d takes %d knight moves.\n",a1,a2,b1,b2,cnt);
    }
    return 0;
}


你可能感兴趣的:(算法,搜索,ACM,bfs,广搜)