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;
}
相关推荐
丢掉幻想准备斗争3 分钟前
5.5树与二叉树的应用
算法
ZhouDevin28 分钟前
算法论文/模型微调2——仅骨干1%~3% 参数达到与全量微调相当的性能
算法
Sinosecu-OCR42 分钟前
文通OCR技术深度解析:自研算法如何搞定复杂场景识别?
算法·ocr·ocr识别系统
CQU_JIAKE1 小时前
8.5【A】
数据结构·算法
ESBK20251 小时前
学术邀约|CMICA 2026 第二届计算方法、智能控制与航空航天国际会议
大数据·人工智能·算法·飞行器·智能控制·航空航天·计算
无bug代码搬运工1 小时前
LeetCode 42 接雨水:双指针解法详解
算法·leetcode·职场和发展
Jasmine_llq2 小时前
《P13016 [GESP202506 六级] 最大因数》
数据结构·算法
白狐_7982 小时前
考研408算法设计题保命策略:链表专题暴力解法精讲(2015 & 2019真题实战)
考研·算法·链表
fangpin2 小时前
GPU编程2: 并行策略
算法
碧海银沙音频科技研究院2 小时前
8基于BES2700IHC数字助听器系统开发
嵌入式硬件·算法