练习2————1015

来源:互联网 发布:淘宝网怎么下载 编辑:程序博客网 时间:2024/05/17 22:44

题目:Knight Moves

题意:根据给出的骑士位置和目标位置,计算骑士最少要走多少步

思路:国际象棋中骑士的走法是在3*2的规格中进行对角线移动,将棋盘表示为9*9,下标从1开始便于计算

            所以有八个方向可以移动,可以设置一组坐标增量来表示这八个方向;

           每走一步都要判断当前步是否还在棋盘上,同时为了避免死循环,还要判断这个位置是否被走过。

感想:如果不了解国际象棋中骑士的走法,题目会有错误,同时死循环真的需要注意。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int c[9][9];
int d[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
string str1,str2;
struct node
{
    int x,y,count;
};
node start,end;
int bfs()
{
    memset(c,0,sizeof(c));
queue<node> q;
    node n1,n2;
    start.count = 0;  
    q.push(start);
    c[start.x][start.y] = 1;
    while(!q.empty())
    {
        n1 = q.front();
        q.pop();
        if(n1.x == end.x&&n1.y == end.y)
        return n1.count;
        for(int i = 0; i < 8; i++)
        {
            n2.x = n1.x + d[i][0];
            n2.y = n2.y + d[i][1];
            if(n2.x<1||n2.x>8||n2.y<1||n2.y>8)continue;
            if(c[n2.x][n2.y]==1)continue;
            c[n2.x][n2.y] = 1;
            n2.count = n1.count + 1;
            q.push(n2);
        }
    }
    return -1;
}
int main()
{
    char row,en;
    int col,ed;
    int min;
    while(scanf("%c",&row)!=EOF)
    {
        scanf("%d",&col);
        getchar();
        scanf("%c%d",&en,&ed);
        getchar();
        start.x = row-'a'+1;
        start.y = col;
        end.x = en-'a'+1;
        end.y = ed;
        if(start.x==end.x&&start.y==end.y)
        min = 0;
        else  min = bfs();
        printf("To get from %c%d to %c%d takes %d knight moves.\n",row,col,en,ed,min);
    }
    return 0;
}


0 0