439 - Knight Moves (UVA)

题目链接如下:

Online Judge

UVA439 骑士的移动 - 锦依卫议事堂 - 洛谷博客 这里有好几个特别厉害的解法...先存着慢慢看。

我的代码如下:

cpp 复制代码
#include <iostream>
#include <deque>
#include <string>
// #define debug

struct node{
    std::string loc;
    int step;
};
std::string s1, s2;
int dx[] = {2, 1, -1, -2, -2, -1, 1, 2};
int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};

int calStep(){
    if (s1 == s2){
        return 0;
    }
    node temp;
    temp.loc = s1;
    temp.step = 0;
    std::deque<node> dq;
    dq.push_back(temp);
    while (!dq.empty()){
        node curr = dq.front();
        dq.pop_front();
        for (int u = 0; u < 8; ++u){
            node tmp;
            tmp.loc.push_back(curr.loc[0] + dx[u]);
            tmp.loc.push_back(curr.loc[1] + dy[u]);
            if (tmp.loc == s2){
                return curr.step + 1;
            }
            if (tmp.loc[0] >= 'a' && tmp.loc[0] <= 'h' && tmp.loc[1] >= '1' && tmp.loc[1] <= '8'){
                tmp.step = curr.step + 1;
                dq.push_back(tmp);
            }
        }
    }
}

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    while (std::cin >> s1 >> s2){
        printf("To get from %s to %s takes %d knight moves.\n", s1.c_str(), s2.c_str(), calStep());
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}
相关推荐
晚云与城5 分钟前
【数据结构】-----排序的艺术画卷
数据结构·算法·排序算法
weixin_3077791320 分钟前
设计Mock CUDA库的流程与实现
c++·算法·gpu算力
j_xxx404_39 分钟前
数据结构:算法复杂度与空间复杂度
c语言·数据结构·算法
dlraba8021 小时前
基于 OpenCV 与 sklearn 的数字识别:KNN 算法实践
opencv·算法·sklearn
yzzzzzzzzzzzzzzzzz1 小时前
leetcode热题——全排列
算法·回溯·全排列
王柏龙1 小时前
mongodb中的哈希索引详解
算法·mongodb·哈希算法
NAGNIP1 小时前
GPT1:通用语言理解模型的开端
后端·算法
NAGNIP1 小时前
GPT-2:让语言模型一统多任务学习江湖
算法
都都学算法1 小时前
【代码走读】DETR-Facebook AI-ECCV 2020
算法
都都学算法1 小时前
【论文通读】OmniDrive-NVIDIA-CVPR 2025
算法