好奇怪的游戏(BFS)

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

int dx[] = {1,1,2,2,-1,-1,-2,-2,2,2,-2,-2};
int dy[] = {2,-2,1,-1,2,-2,1,-1,2,-2,2,-2};

int bfs(int a,int b){
    queue<pair<int,int>> q;
    vector<vector<int>> dis(20,vector<int>(20,-1)); // 20x20的棋盘,初始化所有位置的步数为-1
    dis[a][b] = 0;
    q.push({a,b});


    while(q.size()){
        auto [x,y] = q.front();
        q.pop();

        if(dis[0][0] != -1){//一旦目标位置 (0, 0) 的步数已经被计算出来,直提前结束 BFS。
            return dis[0][0];;
        }

        for(int i=0;i<12;i++){
            int nx = x + dx[i];
            int ny = y + dy[i];

            if(nx>=0 && nx<20 && ny>=0 && ny<20 && dis[nx][ny]==-1){
                dis[nx][ny] = dis[x][y] + 1;// 更新最短步数
                q.push({nx,ny}); // 将新的位置加入队列
            }
        }
    }
    return dis[0][0];
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int x1,x2,y1,y2;
    cin>>x1>>y1>>x2>>y2;
    x1--,x2--,y1--,y2--; // 将坐标调整为0基索引
    cout<<bfs(x1,y1)<<endl;
    cout<<bfs(x2,y2);

    return 0;
}

注意将坐标调整为0基索引

相关推荐
鹿屿二向箔32 分钟前
CCF-GESP(编程能力等级认证)
算法·计算机·考试
安於宿命32 分钟前
【Linux】用C++实现UDP通信:详解socket编程流程
linux·c++·udp
想跑步的小弱鸡33 分钟前
Leetcode hot 100(last day)
算法·leetcode·哈希算法
愚润求学1 小时前
【C++】list模拟实现
开发语言·数据结构·c++·list
hxung4 小时前
B+树与红黑树
数据结构·b树
龙俊杰的读书笔记5 小时前
[leetcode] 面试经典 150 题——篇9:二叉树(番外:二叉树的遍历方式)
数据结构·算法·leetcode·面试
刚入门的大一新生6 小时前
C++初阶-C++的讲解1
开发语言·c++
sml259(劳改版)7 小时前
数据结构--堆
数据结构·算法·
ALex_zry8 小时前
C++17模板编程与if constexpr深度解析
开发语言·c++·性能优化
独家回忆3649 小时前
每日算法-250409
算法