残缺的棋盘

本文介绍了一道关于BFS搜索算法的经典模板题,详细解释了如何使用BFS解决类似迷宫的问题,并提供了完整的C++代码实现。文章通过具体实例展示了如何设定起点、终点以及如何遍历寻找最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<cstdio>

#include<cstring>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
int vis[8][8];
int dx[]={-1,1,0,0,-1,-1,1,1};
int dy[]={0,0,-1,1,-1,1,-1,1};
int r1,c1,r2,c2,r3,c3;
int kstart ,kend;


struct node
{
    int x,y,step;
};
queue<node>Q;
int  BFS(int x1,int y1)
{
        while(!Q.empty())
            Q.pop();
        node u,next;
        u.x = x1;
        u.y = y1;
        u.step = 0;
        vis[u.x][u.y] = 1;
        Q.push(u);
        while(!Q.empty())
        {
            node front = Q.front();
            Q.pop();
            if(front.x == r2&&front.y == c2)
            {
                return front.step;
            }
            int r = front.x;
            int l = front.y;
            for(int i=0;i<8;i++)
            {
                int nx = r+dx[i];
                int ny = l+dy[i];
                next.x =nx;
                next.y = ny;
                if(nx<0||ny<0||nx>=8||ny>=8||vis[nx][ny] == 1||(nx==r3&&ny==c3))
                    continue;
                vis[nx][ny] = 1;
                next.step = front.step + 1;
                Q.push(next);
            }
        }
        return -1;
}
int main()
{
    int count1 = 1;
    while(~scanf("%d%d%d%d%d%d",&r1,&c1,&r2,&c2,&r3,&c3))
    {
        memset(vis,0,sizeof(vis));
        int ans;
        r1--,c1--,r2--,c2--,r3--,c3--;
        ans = BFS(r1,c1);
        printf("Case %d: %d\n",count1++,ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值