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;
}
相关推荐
带多刺的玫瑰23 分钟前
Leecode#26刷题之删除有序数组中的重复项
数据结构·算法·leetcode
en.en..1 小时前
C语言核心解析:#define与typedef本质区别
开发语言·c++·算法
wabs6663 小时前
关于二叉树【429.N叉树的层序遍历的思考】
数据结构·c++·算法·leetcode·二叉树
hetao17338373 小时前
2026-09-08 hetao1733837 的刷题记录
c++·算法
C++ 老炮儿的技术栈4 小时前
MFC CPtrArray的用法
开发语言·数据结构·c++·算法·mfc·c
weixin_446260854 小时前
CABAL:用于追踪同行评审中合谋投标影响的多智能体仿真框架
人工智能·算法·机器学习
不会就选b4 小时前
算法日常・每日刷题--<贪心>6
数据结构·算法·leetcode
青山木4 小时前
Hot 100 --- 跳跃游戏 II
java·数据结构·算法·leetcode·贪心算法
Tisfy4 小时前
LeetCode 3870.统计范围内的逗号:模拟 或 一步计算
数学·算法·leetcode·题解·模拟·遍历
明月_清风5 小时前
字符串匹配四大经典算法:BF、RK、BM、KMP 到底有什么区别?
后端·算法