好奇怪的游戏(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基索引

相关推荐
风中的微尘2 小时前
39.网络流入门
开发语言·网络·c++·算法
混分巨兽龙某某3 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
西红柿维生素3 小时前
JVM相关总结
java·jvm·算法
小冯记录编程3 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
1uther4 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
C_Liu_4 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan4 小时前
【C++】类和对象1
java·开发语言·c++
2501_918126914 小时前
用html5写一个flappybird游戏
css·游戏·html5
阿昭L4 小时前
MFC仿真
c++·mfc
ChillJavaGuy5 小时前
常见限流算法详解与对比
java·算法·限流算法