제출 #976030

#제출 시각아이디문제언어결과실행 시간메모리
976030vjudge1Awesome Arrowland Adventure (eJOI19_adventure)C++17
100 / 100
109 ms10704 KiB
#include<bits/stdc++.h>
using namespace std;

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

bool between(int x, int l, int r) {
    return l <= x && x <= r;
}

const int MAXN = 500;
const int INF = 1e9;
typedef tuple<int, int, int, int> state;

int N, M;
string GRID[MAXN + 5];
int dist[MAXN + 5][MAXN + 5][5];
priority_queue<state, vector<state>, greater<state> > PQ;

 bool inside(int x, int y) {
    return between(x, 0, N - 1) && between(y, 0, M - 1);
}
 int getDir(char c) {
    if (c == 'N') return 0;
    if (c == 'E') return 1;
    if (c == 'S') return 2;
    if (c == 'W') return 3;
    return 4;
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin >> N >> M;
    for (int i = 0; i < N; i++) cin >> GRID[i];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            for (int k = 0; k < 5; k++) {
                dist[i][j][k] = INF;
            }
        }
    }

    dist[0][0][getDir(GRID[0][0])] = 0;
    PQ.push({0, 0, 0, getDir(GRID[0][0])});
    while (!PQ.empty()) {
        auto [cost, x, y, d] = PQ.top();
        PQ.pop();

        if (d == 4) continue;
        // jalan mengikut arah panah
        int nx = x + dx[d], ny = y + dy[d];
        if (inside(nx, ny)) {
            int nd = getDir(GRID[nx][ny]);
            if (dist[nx][ny][nd] > cost) {
                dist[nx][ny][nd] = cost;
                PQ.push({cost, nx, ny, nd});
            }
        }
        // diam tapi berputar arah
        int nd = (d + 1) % 4;
        if (dist[x][y][nd] > cost + 1) {
            dist[x][y][nd] = cost + 1;
            PQ.push({cost + 1, x, y, nd});
        }
    }
    if (dist[N - 1][M - 1][4] == INF) cout << -1 << endl;
    else cout << dist[N - 1][M - 1][4] << endl;
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...