bfs

#include <cstdio>

#include <queue>

#include <utility>//pair

using namespace std;

 

typedef pair<int, int> pii;

const int N = 405;

 

int d[N][N];

 

int main() {

    int n, m, a, b;

    scanf("%d%d%d%d", &n, &m, &a, &b);

    a--, b--;

 

    for (int i = 0; i < n; ++i) {

        for (int j = 0; j < m; ++j) {

            d[i][j] = -1;

        }

    }

    d[a][b] = 0;

 

    queue<pii> q;

    q.push(pii(a, b));

    while (!q.empty()) {

        pii p = q.front();//包括下面一行,这两行是bfs的核心

        q.pop();//后弹出,因为之前只是取出,并没有弹出

        int x = p.first, y = p.second;

        int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2};

        int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};

        for (int i = 0; i < 8; ++i) {

            int nx = x + dx[i], ny = y + dy[i];

            if (0 <= nx && nx < n && 0 <= ny && ny < m && d[nx][ny] == -1) {

                d[nx][ny] = d[x][y] + 1;

                q.push(pii(nx, ny));//把这个点衍生的所有点推入队列

            }

        }

    }

 

    for (int i = 0; i < n; ++i) {

        for (int j = 0; j < m; ++j) {

            printf("%-5d", d[i][j]);

        }

        puts("");

    }

}

这篇文章,是又一个故事的结束...
lazy's story is continuing.
原文地址:https://www.cnblogs.com/Hello-world-hello-lazy/p/14365112.html