求教

P11228 [CSP-J 2024] 地图探险

Flying_Eagle @ 2024-11-04 18:56:01

TLE1&2 80pts

#include <iostream>
#include <cstring>
using namespace std;
int t;
int n, m, k, x0s, y0s, d0s;
const int N = 1e3 + 5;
int a[N][N];
char str[N];

int main() {
//  freopen("explore.in", "r", stdin);
//  freopen("explore.out", "w", stdout);
    scanf("%d", &t);
    while (t--) {
        scanf("%d%d%d%d%d%d", &n, &m, &k, &x0s, &y0s, &d0s);
        memset(a, 0, sizeof(a));
        for (int i = 1; i <= n; i++) {
            scanf("%s", str);
            for (int j = 0; j < m; j++) {
                if (str[j] == 'x')
                    a[i][j + 1] = 0;
                else
                    a[i][j + 1] = 1;
            }
        }
        a[x0s][y0s] = -1;
        int step = 0, x = x0s, y = y0s, d = d0s;
        while (step < k) {
            step++;
            int nowx, nowy;
            if (d == 0) {
                nowx = x;
                nowy = y + 1;
            } else if (d == 1) {
                nowx = x + 1;
                nowy = y;
            } else if (d == 2) {
                nowx = x;
                nowy = y - 1;
            } else {
                nowx = x - 1;
                nowy = y;
            }
            while (nowx > n || nowx <= 0 || nowy > m || nowy <= 0 || a[nowx][nowy] == 0) {
                d = (d + 1) % 4;
                if (d == 0) {
                    nowx = x;
                    nowy = y + 1;
                } else if (d == 1) {
                    nowx = x + 1;
                    nowy = y;
                } else if (d == 2) {
                    nowx = x;
                    nowy = y - 1;
                } else {
                    nowx = x - 1;
                    nowy = y;
                }
                step++;
            }
            if (step > k)
                break;
            a[nowx][nowy] = -1;
            x = nowx, y = nowy;
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (a[i][j] == -1)
                    ans++;
            }
        }
        cout << ans << endl;
    }

    return 0;
}

|