求助 BFS #1 WA
查看原帖
求助 BFS #1 WA
1028403
封禁用户楼主2024/5/29 17:53

rt,Wrong Answer.wrong answer on case 35 you are not at termination

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 2e3 + 10;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int T, n, m, cur, dp[N][N];
char a[N][N], ans[N];
struct Node {
    int x, y;
};
queue<Node> q;
void init() {
    memset(dp, -1, sizeof dp);
    memset(ans, ' ', sizeof ans);
    while (!q.empty()) q.pop();
    q.push({1, 1});
    dp[1][1] = 0;
}
char solve(int x) {
    if (x == 0) return 'U';
    if (x == 1) return 'D';
    if (x == 2) return 'L';
    if (x == 3) return 'R';
}
void bfs() {
    while (!q.empty()) {
        Node p = q.front();
        q.pop();
        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 <= m && 
                dp[kx][ky] == -1 && a[kx][ky] != a[p.x][p.y]) {
                    q.push({kx, ky});
                    dp[kx][ky] = dp[p.x][p.y] + 1;
                    ans[++cur] = solve(i);
                }
        }
    }
}
int main()
{
    cin >> T;
    while (T--) {
        cur = 0;
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                cin >> a[i][j];
        init();
        bfs();
        if (dp[n][m] == -1)
            cout << -1 << endl;
        else {
            cout << dp[n][m] << endl;
            for (int i = 1; i <= dp[n][m]; i++)
                cout << ans[i];
            cout << endl;
        }
    }
    return 0;
}
2024/5/29 17:53
加载中...