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;
}
相关推荐
wabs6661 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin031 小时前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode
shehuiyuelaiyuehao2 小时前
算法50,分治归并,数组中的逆序对
java·算法
阳明山水2 小时前
校准分位数驱动智能库存决策
人工智能·深度学习·算法·机器学习·架构
别动我齐刘海3 小时前
ROS2 Jazzy + C++ 实战路线——进阶学习3
c++·人工智能·vscode·python·算法·机器学习·机器人
zhangfeng11334 小时前
《从“人工适配“到“智能生成“:KernelSwift 跨国产芯片算子迁移全栈方案解读》 —— 强调范式跃迁和跨硬件属性,适合偏架构分析的写法
人工智能·算法·华为·ai编程·npu
0+1114 小时前
算法 --滑动窗口
c++·算法·leetcode
reikocao4 小时前
大场景下 Hessian 特征值放大与退化检测
算法
hetao17338374 小时前
2026-09-18 hetao1733837 的刷题记录
c++·算法
wuyk5555 小时前
21.计数排序:不用比较的“空间换时间”排序算法
python·算法·排序算法