1015

题目大意:
国际象棋中骑士的走法。从a到b的最少步数

思路形成过程:
看到最少,想到BFS
刚看到这个提的output这么长本以为要输出走的路径,要是这样的话做起来就难多了
遇到一个小问题:如果队列不清空会出错

freopen(“1”,”r”,stdin);
这样读入一个没有后缀的文件也可以,太神奇了

代码

//Knight Moves
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;

bool map[9][9];
int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
struct Knight
{
    int x,y;
    int step;
}k1,k2;
queue<Knight> Q;

int BFS(int sx,int sy,int ex,int ey)
{
    while(Q.size())
    {
        Q.pop();
    }
    memset(map,0,sizeof(map));
    k1.step=0;
    k1.x=sx;
    k1.y=sy;
    Q.push(k1);
    while(Q.size())
    {
        k1=Q.front();
        Q.pop();
        if(k1.x<1||k1.x>8||k1.y<1||k1.y>8)  continue;
        if(map[k1.x][k1.y]==1)  continue;
        else map[k1.x][k1.y]=1;
        if(k1.x==ex&&k1.y==ey)  
        {
            return k1.step;
        }
        for(int i=0;i<8;i++)
        {
            k2.x=k1.x+dir[i][0];
            k2.y=k1.y+dir[i][1];
            k2.step=k1.step+1;
            Q.push(k2);
        }
    }
    return -1;
}

int main()
{
    freopen("1","r",stdin);
    char a,c;
    int b,d;
    int temp;
    while(cin>>a>>b>>c>>d)
    {   
        temp=BFS(a+1-'a',b,c+1-'a',d);
        cout<<"To get from "<<a<<b<<" to "<<c<<d<<" takes "<<temp<<" knight moves."<<endl;
    }

}

你可能感兴趣的:(1015)