现在的位置: 首页 > 综合 > 正文

POJ 2243 || HDU 1372:Knight Moves(BFS)

2018年01月17日 ⁄ 综合 ⁄ 共 764字 ⁄ 字号 评论关闭

简单搜索

直接代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
char a,c;
int e,f;
int dx[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
int dy[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
int qq[9][9];
struct node
{
    int q,w,num;
};
node b,d;
queue<node> q;
void bfs()
{
    int i;
    while(!q.empty())
    {
        node temp=q.front();
        q.pop();
        if(temp.q==d.q&&temp.w==d.w)
        {
            printf("To get from %c%d to %c%d takes %d knight moves.\n",a,b.w,c,d.w,temp.num);
            return ;
        }
        else
        {
            for(i=0;i<8;i++)
            {
                int xx=temp.q+dx[i];
                int yy=temp.w+dy[i];
                if(!qq[xx][yy]&&xx>0&&xx<=8&&yy<=8&&yy>0)
                {
                    qq[xx][yy]=1;
                    node next;
                    next.q=xx;
                    next.w=yy;
                    next.num=temp.num+1;
                    q.push(next);
                }
            }
        }
    }
}

int main()
{
    while(~scanf("%c%d %c%d",&a,&b.w,&c,&d.w))
    {
        getchar();
        while(!q.empty())  q.pop();
        memset(qq,0,sizeof(qq));
        b.q=a-'a'+1;
        d.q=c-'a'+1;
        b.num=0;
        qq[b.q][b.w]=1;
        q.push(b);
        bfs();
    }
    return 0;
}

抱歉!评论已关闭.