洛谷 P1443

P1443

所屬知識點:BFS

傳送門node

題意 :

給你一個矩陣和一匹馬一開始的位置.而後問你在這個矩陣裏邊跳到每個點須要多少步.c++

思路:

由於一匹馬從一個點能夠跳到的位置以下圖:

畫的很差請見諒...git

咱們就能夠開始進行bfs了,最好的板子題.spa

而後最後輸出的時候由於要留5個長寬.
能夠這樣搞:3d

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;
}
相關文章
相關標籤/搜索