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;
}
相关推荐
渡之4 分钟前
GeoBridge 深度解析:语义锚定多视图基础模型,重塑无人机跨视角地理定位
深度学习·算法·动态规划·无人机
一口吃俩胖子8 分钟前
【脉宽调制DCDC功率变换学习笔记024】电压反馈补偿和环路增益
笔记·学习·算法
洛水水12 分钟前
【力扣100题】80.寻找旋转排序数组中的最小值
数据结构·算法·leetcode
ting945200013 分钟前
VC Boom 技术架构与核心算法深度解
人工智能·算法·架构
无限码力17 分钟前
美团研发岗 5月9号笔试真题 - 正整数矩阵
算法·美团笔试真题·美团研发岗笔试真题·美团0509笔试真题
Smilecoc20 分钟前
决策树(二):决策树的划分选择
算法·决策树·机器学习
hetao173383731 分钟前
2026-05-25~06-11 hetao1733837 的刷题记录
c++·算法
cheems952735 分钟前
[算法手记] 滑动窗口最大值
算法
洛水水36 分钟前
【力扣100题】82.有效的括号
c++·算法·leetcode
XGeFei38 分钟前
时序算法 —— LSTM、ARIMA、随机森林
算法·随机森林·lstm