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;
}
相关推荐
ab1515173 分钟前
2.18完成109、112、113
算法
追随者永远是胜利者30 分钟前
(LeetCode-Hot100)64. 最小路径和
java·算法·leetcode·职场和发展·go
汉克老师36 分钟前
GESP2024年6月认证C++二级( 第三部分编程题(1) 平方之和)
c++·算法·预处理·完全平方数·循环结构·gesp二级·gesp2级
云深处@1 小时前
【题】每日一题
算法
智者知已应修善业1 小时前
【排列顺序判断是否一次交换能得到升序】2025-1-28
c语言·c++·经验分享·笔记·算法
yzs872 小时前
OLAP数据库HashJoin性能优化揭秘
数据库·算法·性能优化·哈希算法
好家伙VCC3 小时前
**发散创新:编译器优化实战——从LLVM IR到性能飞跃的奇妙旅程**
java·开发语言·python·算法
季明洵3 小时前
数据在内存中的存储
数据结构·算法·c
weixin_458872613 小时前
东华复试OJ每日3题打卡·复盘85~87
算法
追随者永远是胜利者3 小时前
(LeetCode-Hot100)70. 爬楼梯
java·算法·leetcode·职场和发展·go