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;
}
相关推荐
样例过了就是过了11 分钟前
LeetCode热题100 编辑距离
数据结构·c++·算法·leetcode·动态规划
wearegogog12316 分钟前
MATLAB椭圆参数检测算法实现
数据库·算法·matlab
secondyoung16 分钟前
Markdown数学公式语法速查手册
算法·编辑器·markdown·latex
君义_noip34 分钟前
CSP-S 2025 提高级 第一轮(初赛) 阅读程序(1)
算法·深度优先·信息学奥赛·初赛
小O的算法实验室37 分钟前
2026年IEEE TEVC,知识引导的竞争进化算法用于多解传感器-武器-目标分配问题,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
khalil10201 小时前
代码随想录算法训练营Day-46 动态规划13 | 647. 回文子串、516.最长回文子序列、动态规划总结
数据结构·c++·算法·leetcode·动态规划·回文子串·回文子序列
学习3人组1 小时前
柔性排产时序算法+中间过程+阶段目标 细化表格
算法·mes
he___H1 小时前
算法快与慢--哈希+双指针
算法·leetcode·哈希算法
呃呃本1 小时前
算法题(回溯)
算法
刀法如飞1 小时前
Rust数组去重的20种实现方式,AI时代用不同思路解决问题
人工智能·算法·ai编程