• CF3A Shortest path of the king


    CF3A Shortest path of the king

    Luogu题地址

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    using namespace std;
    const int N = 10;
    int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
    int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
    string s[8] = {"U", "RU", "R", "RD", "D", "LD", "L", "LU"};
    vector<string> ans;
    struct Node{
        int x, y, step;
    }node, S, T;
    
    bool st[N][N];
    int d[N][N];
    Node q[N];
    
    void bfs()
    {
        d[S.x][S.y] = 0;
        queue<Node> q;
        q.push(S);
        st[S.x][S.y] = true;
        while(q.size())
        {
            Node t = q.front();
            q.pop();
    
            int x = t.x, y = t.y, step = t.step;
            d[x][y] = step;
            for(int i = 0; i < 8; i ++)
            {
                int nx = x + dx[i], ny = y + dy[i];
                if(nx >= 0 && nx <= 7 && ny >= 0 && ny <= 7 && !st[nx][ny])
                {
                    node.x = nx, node.y = ny, node.step = step + 1;
                    q.push(node);
                    st[nx][ny] = true;
                }
            }
    
        }
    }
    
    void find(int x, int y)
    {
        for(int i = 0; i < 8; i ++)
        {
            if(x == dx[i] && y == dy[i])
                ans.push_back(s[i]);
        }
    }
    
    int main()
    {
        char s1[3], s2[3];
        cin >> s1 >> s2;
        S = {s1[1] - '1', s1[0] - 'a', 0};
        T = { s2[1] - '1',s2[0] - 'a', 0};
    
        bfs();
        cout << d[T.x][T.y] << endl;
        int x = T.x, y = T.y;
        if(d[x][y] == 0) return 0;
    
        while(1)
        {
            bool flag = false;
            for(int i = 0; i < 8; i ++)
            {
                int nx = x + dx[i], ny = y + dy[i];
                if(nx < 0 || nx > 7 || ny < 0 || ny > 7) continue;
                if(d[nx][ny] == 0)
                {
                    find(x - nx, y - ny);
                    flag = true;
                    break;
                }
                if(d[nx][ny] == d[x][y] - 1)
                {
                    find(x - nx, y - ny);
                    x = nx, y = ny;
                    continue;
                }
    
            }
            if(flag == true) break;
        }
        int len = ans.size() - 1;
        for(int i = len; i >= 0; i --)
            cout << ans[i] << endl;
    }
  • 相关阅读:
    cs
    PC管理端与评委云打分配合步骤及疑难问题汇编,即如何使用PC管理端的云服务管理功能
    B.数据结构(栈和队列)
    13.Python(模块)
    A.数据结构(线性表)
    c.Matlab(数据和函数的可视化)
    b.Matlab(字符串)
    12.Python(装饰器)
    11.Python(生成器)
    10.Python(高级特性)
  • 原文地址:https://www.cnblogs.com/longxue1991/p/13093679.html
Copyright © 2020-2023  润新知