zoukankan      html  css  js  c++  java
  • P1443 马的遍历题解

    题目传送门

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int n, m;       //n*m的棋盘
    int x, y;       //马的位置
    const int N = 410;
    int ans[N][N]; //到任意点需要最少走几步
    //坐标
    struct coord {
        int x, y;
    };
    queue<coord> q;
    //马的八大方向坐标位移
    int walk[8][2] = {{2,  1},
                      {1,  2},
                      {-1, 2},
                      {-2, 1},
                      {-2, -1},
                      {-1, -2},
                      {1,  -2},
                      {2,  -1}};
    
    int main() {
        //输入棋盘大小和马的位置
        cin >> n >> m >> x >> y;
    
        //标识为-1,表示没有探索过
        memset(ans, -1, sizeof ans);
    
        //马入队列
        q.push({x, y});
        ans[x][y] = 0;//出发点标识为最少走0步
    
        while (!q.empty()) {
            coord u = q.front();
            q.pop();
            for (int k = 0; k < 8; k++) {//8个方向
                int x = u.x + walk[k][0], y = u.y + walk[k][1];//可能达到的下一步坐标
                if (x < 1 || x > n || y < 1 || y > m || ans[x][y] != -1)continue;
                //步数等于上一级来的位置+1
                ans[x][y] = ans[u.x][u.y] + 1;
                //入队列
                q.push({x, y});
            }
        }
        //输出结果
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++)
                printf("%-5d", ans[i][j]); //左对齐
            puts("");
        }
        return 0;
    }
    
  • 相关阅读:
    基于python的种子搜索网站(三)项目部署
    Python 的 Geth 封装库 PyGeth
    主题: 002.04 Tkinter 星空大战
    python 打飞机项目 (实战一)
    python使用mysql的一些坑
    Python 变量与运算符
    字符流
    IO字节流(2)
    端口转发
    IO流(1)
  • 原文地址:https://www.cnblogs.com/littlehb/p/15062337.html
Copyright © 2011-2022 走看看