怎么实现啊求助(思路:广度优先搜索)(c++)
查看原帖
怎么实现啊求助(思路:广度优先搜索)(c++)
794507
_VirtualPoint_楼主2023/7/13 20:27

先给个代码模板(这个是我做另外一题的代码):

//P1443 马的遍历

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

const int MAX = 4*1e2+5;

int x1, x2, y1__, y2;
int n, m;
int step[MAX][MAX];
string g[MAX][MAX];

struct State {
    int x, y;
};

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


bool inside(int x, int y) {
    return 1 <= x && x <= n && 1 <= y && y <= m;
}

void print() {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cout << step[i][j] << " ";
        }
        cout << endl;
    }
}

void bfs(int x1, int y1__) {
    queue<State> que;
    memset(step, -1, sizeof(step));
    step[x1][y1__] = 0;
    que.push(State{x1, y1__});
    while (!que.empty()) {
        State s = que.front();
        que.pop();
        for (int d = 0; d < 8; d++) {
            int x = s.x + dx[d], y = s.y + dy[d];
            if (!inside(x, y) || step[x][y] != -1) continue;
            step[x][y] = step[s.x][s.y] + 1;
            que.push(State{x, y});
        }
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin >> n >> m >> x1 >> y1__;

    bfs(x1, y1__);
    print();

    return 0;
}
2023/7/13 20:27
加载中...