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;
}
相关推荐
南宫萧幕12 分钟前
HEV 智能能量管理实战:从 MPC/PPO 理论解析到 Python-Simulink 联合仿真闭环全流程
开发语言·python·算法·matlab·控制
啦啦啦_999913 分钟前
1. 一元/多元线性回归之 正规方程求解法
算法·回归·线性回归
ECT-OS-JiuHuaShan31 分钟前
整体论体系定理,全球开放,无法绕过
人工智能·科技·学习·算法·生活
贾斯汀玛尔斯1 小时前
每天学一个算法--BM25(Okapi BM25)
算法
grant-ADAS1 小时前
Overlay套刻测量
算法
猿长大人1 小时前
算法 | Douglas-Peucker 拯救“腰椎间盘突出的三角形”
算法
HackTorjan2 小时前
深度解析雪花算法及其高性能优化策略
人工智能·深度学习·算法·性能优化·dreamweaver
北顾笙9802 小时前
day35-数据结构力扣
数据结构·算法·leetcode
cpp_25012 小时前
P2249 【深基13.例1】查找
数据结构·c++·算法·题解·二分·洛谷
烤麻辣烫2 小时前
算法--二分搜索
java·开发语言·学习·算法·intellij-idea