跳到正文

题解

P12270 [蓝桥杯 2024 国 Python B] 马与象

cyc27约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年7月8日
收录
2026年7月9日
更新
2026年11月10日
篇幅
约 5 分钟
题目
P12270

版本

  1. v1当前

思路

这道题的最优解最好用广度优先搜索 BFS 来做,其实吃掉就代表他们的位置在同一个地方,首先遍历棋盘里的每一个点,将每一个点马走到这个位置和象走到这个位置的步数记录下来,如果其中一个走不到的话就换下一个点,用一个变量来记录可以达到的每一个点的最短路径,最后输出。

注:此题用map嵌套pair去重,每次要记得把map给加上,还有一个建议是用queue来写,第一次入队也得把map加上,推荐在队首出队的时候判断是否到达,否则就无法判断起点等于终点的情况,每次判断都要先判断越界再判断其他的。

代码实现

  • 用双层for循环遍历每一个点
  • 在每一个点上分别进行BFS
  • 将结果输出

code:

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
int n,mx,my,xx,xy;//变量
int ans=INT_MAX;
bool h=1;
struct node{
    int x,y,step;
};
queue<node> q;
map<pair<int,int>,bool> mp;
int fang1[8][2]{//定义方向
    {1,2},
    {1,-2},
    {-1,2},
    {-1,-2},
    {2,1},
    {2,-1},
    {-2,1},
    {-2,-1},
};
int fang2[4][2]={
    {2,2},
    {2,-2},
    {-2,2},
    {-2,-2}
};
int bfs1(int ex,int ey){//马的BFS
    q.push({mx,my,0});
    mp[{mx,my}]=1;
    while(q.size()){
        node t=q.front();
        q.pop();
        if(t.x==ex&&t.y==ey){
            return t.step;
        }
        for(int i=0;i<8;i++){
            int nx=t.x+fang1[i][0];
            int ny=t.y+fang1[i][1];
            if(nx<1||nx>n||ny<1||ny>n){
                continue;
            }
            if(mp.count({nx,ny})){
                continue;
            }
            q.push({nx,ny,t.step+1});
            mp[{nx,ny}]=1;
        }
    }
    return -1;
}
int bfs2(int ex,int ey){//象的BFS
    q.push({xx,xy,0});
    mp[{xx,xy}]=1;
    while(q.size()){
        node t=q.front();
        q.pop();
        if(t.x==ex&&t.y==ey){
            return t.step;
        }
        for(int i=0;i<4;i++){
            int nx=t.x+fang2[i][0];
            int ny=t.y+fang2[i][1];
            if(nx<1||ny<1||nx>n||ny>n){
                continue;
            }
            if(mp.count({nx,ny})){
                continue;
            }
            q.push({nx,ny,t.step+1});
            mp[{nx,ny}]=1;
        }
    }
    return -1;
}
signed main(){
    cin>>n>>mx>>my>>xx>>xy;//输入
    n++;
    mx++;
    my++;
    xx++;
    xy++;//将所有从一开始
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){//遍历每个点
            while(q.size()){
                q.pop();
            }
            mp.clear();//记得要清空
            int tmp1=bfs1(i,j);
            while(q.size()){
                q.pop();
            }
            mp.clear();
            int tmp2=bfs2(i,j);
            if(tmp1==-1||tmp2==-1){//只要有一个到不了就都不行
                continue;
            }else{
                ans=min(ans,tmp1+tmp2);
                h=0;
            }
        }
    }
    if(h){//判断
        cout<<-1<<endl;//没有找到答案
    }else{
        cout<<ans<<endl;
    }
    return 0;
}
原文