結果

問題 No.3504 Insert Maze
コンテスト
ユーザー Saku0512
提出日時 2026-04-18 01:42:33
言語 C++23
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 362 ms / 2,000 ms
コード長 1,680 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 3,550 ms
コンパイル使用メモリ 332,216 KB
実行使用メモリ 144,236 KB
最終ジャッジ日時 2026-04-18 01:43:07
合計ジャッジ時間 22,874 ms
ジャッジサーバーID
(参考情報)
judge3_1 / judge1_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 85
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
using namespace std;

const int MAX_NODES = 16000005;
int dist_arr[MAX_NODES];
int q[MAX_NODES];
bool can_enter[MAX_NODES];

int main() {
    cin.tie(0)->sync_with_stdio(0);

    int H, W;
    if (!(cin >> H >> W)) return 0;

    int R = 2 * H - 1;
    int C = 2 * W - 1;

    for (int i = 0; i < H; ++i) {
        string s;
        cin >> s;
        for (int j = 0; j < W; ++j) {
            if (s[j] != '#') {
                can_enter[(i * 2) * C + (j * 2)] = true;
            }
        }
    }

    for (int y = 0; y < R; ++y) {
        for (int x = 0; x < C; ++x) {
            if ((y & 1) || (x & 1)) {
                can_enter[y * C + x] = true;
            }
            dist_arr[y * C + x] = -1;
        }
    }

    int head = 0, tail = 0;
    q[tail++] = 0;
    dist_arr[0] = 0;

    int target = (R - 1) * C + (C - 1);

    while (head < tail) {
        int u = q[head++];
        if (u == target) {
            cout << dist_arr[u] << '\n';
            return 0;
        }

        int y = u / C;
        int x = u % C;
        int d = dist_arr[u] + 1;

        auto push = [&](int v) {
            if (can_enter[v] && dist_arr[v] == -1) {
                dist_arr[v] = d;
                q[tail++] = v;
            }
        };

        if (y > 0) push(u - C);
        if (y + 1 < R) push(u + C);
        if (x > 0) push(u - 1);
        if (x + 1 < C) push(u + 1);

        if (!(x & 1)) {
            if (x > 1) push(u - 2);
            if (x + 2 < C) push(u + 2);
        }
        if (!(y & 1)) {
            if (y > 1) push(u - 2 * C);
            if (y + 2 < R) push(u + 2 * C);
        }
    }

    cout << -1 << '\n';
    return 0;
}
0