完了我不会 BFS 了
查看原帖
完了我不会 BFS 了
1028403
封禁用户楼主2024/6/25 16:52

rt,2 AC + RE + 2 WA 求助 QWQ……

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

const int N = 1000;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};

struct Node {
    int x, y, cnt;
    char last;
};

char a[N][N];
int n, m, sx, sy, zx, zy;
bool vis[N][N];
queue<Node> q;

void Init() {
    while (!q.empty()) q.pop();
    memset(vis, false, sizeof vis);
    q.push((Node){sx, sy, 0, a[sx][sy]});
    vis[sx][sy] = true;
}

int Bfs() {
    while (!q.empty()) {
        Node p = q.front();
        q.pop();
        if (p.x == zx && p.y == zy)
            return p.cnt;
        for (int i = 0; i < 4; i++) {
            int kx = p.x + dx[i];
            int ky = p.y + dy[i];
            if (kx < 1 || kx > n || ky < 1 || ky > n)
                continue;
            if (vis[kx][ky])
                continue;
            vis[kx][ky] = true;
            if (a[kx][ky] != p.last)
                q.push((Node){kx, ky, p.cnt + 1, a[kx][ky]});
            else
                q.push((Node){kx, ky, p.cnt, p.last});
        }
    }
}

int main() {
    while (cin >> n >> m && n && m) {
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                cin >> a[i][j];
        cin >> sx >> sy >> zx >> zy;
        sx++, sy++, zx++, zy++;
        Init();
        cout << Bfs() << "\n";
    }
    return 0;
}
2024/6/25 16:52
加载中...