hiho一下 第九十九周

Problem: 搜索二·骑士问题
Description: 国际象棋棋盘中有三个马,问这三个马最少走几步能走到同一个格子。一次只能走一个棋子。
Solution: 基础的广搜题目,用一个6维数组保存当前状态。
Code(C++):

#include <stdio.h>
#include <string.h>

typedef struct tagPoint{
    int x,y;
    tagPoint(){}
    tagPoint(int x,int y)
    {
        this->x=x;
        this->y=y;
    }
    bool operator==(tagPoint &o)
    {
        return this->x==o.x&&this->y==o.y;
    }
}Point;

typedef struct tagNode{
    Point a[3];
    int step;
    tagNode(){}
    tagNode(Point a[],int step)
    {
        for(int i=0;i<3;i++)
            this->a[i]=a[i];
        this->step=step;
    }
    bool operator==(tagNode &o)
    {
        return a[0]==a[1]&&a[1]==a[2];
    }
}Node;

const int QUEUE_TOP=10000000;

const int dirx[]={-2,2,1,-1,-2,2,1,-1,};
const int diry[]={1,1,2,2,-1,-1,-2,-2,};

Point points[3];

Node que[QUEUE_TOP];
int head,tail;

bool used[9][9][9][9][9][9];

int bfs()
{
    if(points[0]==points[1]&&
        points[1]==points[2]){
        return 0;
    }

    head=tail=0;
    memset(used,false,sizeof(used));

    que[tail++]=Node(points,0);
    used[points[0].x][points[0].y][points[1].x][points[1].y][points[2].x][points[2].y]=true;
    while(tail!=head){
        Node pre=que[head++];
        head%=QUEUE_TOP;

        for(int i=0;i<3;i++)
            for(int j=0;j<8;j++){
                Point now_point=Point(pre.a[i].x+dirx[j],
                                        pre.a[i].y+diry[j]);
                Node now=pre;
                ++now.step;
                now.a[i]=now_point;
                if(!(now_point.x>=1&&now_point.x<=8&&now_point.y>=1&&now_point.y<=8))
                    continue;
                if(now.a[0]==now.a[1]&&now.a[1]==now.a[2])
                    return now.step;
                if(!used[now.a[0].x][now.a[0].y][now.a[1].x][now.a[1].y][now.a[2].x][now.a[2].y]){
                    used[now.a[0].x][now.a[0].y][now.a[1].x][now.a[1].y][now.a[2].x][now.a[2].y]=true;
                    que[tail++]=now;
                    tail%=QUEUE_TOP;
                }
            }
    }
    return 0;
}

int main()
{
    int N;
    for(scanf("%d",&N);N--;){
        char a[3][3];
        for(int i=0;i<3;i++){
            scanf("%s",a[i]);
            points[i]=Point(a[i][0]-'A'+1,a[i][1]-'0');
        }

        int ans=bfs();

        printf("%d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值