ZCMU1639 残缺的棋盘

ZCMU1639 残缺的棋盘

Description

在国际象棋里,王是最重要的一个棋子。每一步,王可以往上下左右或者对角线方向移动一步,如下图所示。

给定两个格子 A(r1,c1), B(r2,c2),你的任务是计算出一个王从 A 到 B 至少需要走多少步。为了避免题目太简单,我们从棋盘里拿掉了一个格子 C(r3,c3)(ABC 保证互不相同),要求王从 A走到 B 的过程中不能进入格子 C。在本题中,各行从上到下编号为 1~8,各列从左到右编号为1~8。

Input

输入包含不超过 10000 组数据。每组数据包含 6 个整数 r1, c1, r2, c2, r3, c3 (1<=r1, c1, r2, c2, r3, c3<=8). 三个格子 A, B, C 保证各不相同。

Output

对于每组数据,输出测试点编号和最少步数

Sample Input

1 1 8 7 5 6

1 1 3 3 2 2

Sample Output

Case 1: 7

Case 2: 3

 

思路

用广度优先搜索算法(BFS)找最短路径。

注意

这里每个点可以朝八个方向走。

代码

#include<bits/stdc++.h>
using namespace std;
int r1,c1,r2,c2,r3,c3;
struct note
{
    int x;
    int y;
    int f;
    int s;
};
int main()
{
    struct note que[65];
    int a[9][9],book[9][9];
    int next[8][2]={{0,1},{1,0},{0,-1},{-1,0},{1,1},{1,-1},{-1,-1},{-1,1}};
    int head,tail;
    int i,j,k,n,m,r1,c1,r2,c2,r3,c3,tx,ty,flag;
    int sum=0;
    while(~scanf("%d %d %d %d %d %d",&r1,&c1,&r2,&c2,&r3,&c3))
    {
        fill(a[0],a[0]+81,1);
        memset(book,0,sizeof(book));
        a[r3][c3]=0;
        head=1;
        tail=1;
        que[tail].x=r1;
        que[tail].y=c1;
        que[tail].f=0;
        que[tail].s=0;
        tail++;
        book[r1][c1]=1;
        flag=0;
        while(head<tail)
        {
            for(k=0;k<=7;k++)
            {
                tx=que[head].x+next[k][0];
                ty=que[head].y+next[k][1];
                if(tx<1||tx>8||ty<1||ty>8)
                    continue;
                if(a[tx][ty]==1&&book[tx][ty]==0)
                {
                    book[tx][ty]=1;
                    que[tail].x=tx;
                    que[tail].y=ty;
                    que[tail].f=head;
                    que[tail].s=que[head].s+1;
                    tail++;
                }
                if(tx==r2&&ty==c2)
                {
                    flag=1;
                    break;
                }
            }
            if(flag==1)
                break;
            head++;
        }
        printf("Case %d:% d\n",++sum,que[tail-1].s);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值