首页 > 其他 > 详细

洛谷 P1443

时间:2019-10-19 12:28:02      阅读:63      评论:0      收藏:0      [点我收藏+]

P1443

所属知识点:BFS

传送门

题意 :

给你一个矩阵和一匹马一开始的位置.然后问你在这个矩阵里边跳到每一个点需要多少步.

思路:

因为一匹马从一个点可以跳到的位置如下图:
技术分享图片
画的不好请见谅...

我们就可以开始进行bfs了,最好的板子题.

然后最后输出的时候因为要留5个长宽.
可以这样搞:

            cout << setw(5) << std::left << maze[i][j];

code:

#include <bits/stdc++.h>
#include <queue>
#define N 100010
#define M 1010
#define _ 0

using namespace std;
struct node {
    int x, y, bushu;
};
int m, n, x, y;
int u[8]= {1, 2, 2, 1, -1, -2, -2, -1};
int v[8]= {-2, -1, 1, 2, 2, 1, -1, -2};
int maze[401][401];
queue<node> q;

int read() {
    int s = 0, f = 0; char ch = getchar();
    while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
    while (isdigit(ch)) s = s * 10 + (ch ^ 48), ch = getchar();
    return f ? -s : s;
}

void bfs(int r, int t) {
    memset(maze, -1, sizeof(maze));
    maze[r][t] = 0;
    q.push((node) {r, t, 0});
    while (!q.empty()) {
        node a = q.front();
        q.pop();
        for (int i = 0; i <= 7; i++) {
            int fx = a.x + u[i];
            int fy = a.y + v[i];
            if (fx >= 1 && fx <= n && fy >= 1 && fy <= m && maze[fx][fy] == -1) {
                maze[fx][fy] = a.bushu + 1;
                q.push((node) {fx, fy, a.bushu + 1}); 
            }
        }
    }
}

int main() {
    n = read(), m = read(), x = read(), y = read();
    bfs(x, y);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) 
            cout << setw(5) << std::left << maze[i][j];
        puts("");
    }
    return 0^_^0;
}

洛谷 P1443

原文:https://www.cnblogs.com/zzz-hhh/p/11703349.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!