結果

問題 No.157 2つの空洞
ユーザー ふーらくたるふーらくたる
提出日時 2016-07-02 02:58:08
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,699 bytes
コンパイル時間 585 ms
コンパイル使用メモリ 65,948 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-04-20 06:50:41
合計ジャッジ時間 1,236 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,816 KB
testcase_01 AC 2 ms
6,940 KB
testcase_02 AC 1 ms
6,944 KB
testcase_03 AC 1 ms
6,944 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 1 ms
6,944 KB
testcase_06 AC 1 ms
6,944 KB
testcase_07 AC 2 ms
6,940 KB
testcase_08 AC 2 ms
6,940 KB
testcase_09 AC 2 ms
6,940 KB
testcase_10 AC 1 ms
6,940 KB
testcase_11 AC 1 ms
6,948 KB
testcase_12 AC 1 ms
6,944 KB
testcase_13 AC 2 ms
6,944 KB
testcase_14 AC 1 ms
6,940 KB
testcase_15 AC 2 ms
6,940 KB
testcase_16 AC 1 ms
6,944 KB
testcase_17 AC 1 ms
6,944 KB
testcase_18 AC 1 ms
6,944 KB
testcase_19 AC 1 ms
6,940 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

struct State {
    int row, col, times;
};

const int kMAX_W = 30;
const int kMAX_H = 30;

int W, H;
string C[kMAX_H];
bool used[kMAX_H][kMAX_W];
bool is_start[kMAX_H][kMAX_W];

int dr[4] = {1, 0, -1, 0},
    dc[4] = {0, 1, 0, -1};

// 一つ目の空洞部分を調べる
void DFS(int r, int c, queue<State>& que) {
    used[r][c] = true;
    is_start[r][c] = true;
    que.push((State){r, c, 0});

    for (int i = 0; i < 4; i++) {
        int nr = r + dr[i], nc = c + dc[i];
        if (0 <= nr && nr < H && 0 <= nc && nc < W &&
                !used[nr][nc] && C[nr][nc] == '.') {
            DFS(nr, nc, que);
        }
    }
}

void Solve() {
    queue<State> que;
    for (int r = 0; r < H; r++) {
        bool find_cave = false;
        for (int c = 0; c < W; c++) {
            if (C[r][c] == '.') {
                DFS(r, c, que);
                find_cave = true;
                break;
            }
        }
        if (find_cave) break;
    }

    while (!que.empty()) {
        State s = que.front(); que.pop();
        if (C[s.row][s.col] == '.' && !is_start[s.row][s.col]) {
            cout << s.times << endl;
            return;
        }
        for (int i = 0; i < 4; i++) {
            int nr = s.row + dr[i], nc = s.col + dc[i];
            if (0 <= nr && nr < H && 0 <= nc && nc < W && !used[nr][nc]) {
                int times = s.times + (C[nr][nc] == '#' ? 1 : 0);
                used[nr][nc] = true;
                que.push((State){nr, nc, times});
            }
        }
    }
}

int main() {
    cin >> W >> H;

    for (int i = 0; i < H; i++) {
        cin >> C[i];
    }

    Solve();

    return 0;
}
0