結果

問題 No.157 2つの空洞
ユーザー granddaifukugranddaifuku
提出日時 2020-03-26 14:51:34
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 3 ms / 2,000 ms
コード長 1,947 bytes
コンパイル時間 1,831 ms
コンパイル使用メモリ 177,692 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-08-30 12:38:25
合計ジャッジ時間 3,184 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

#define rep(i, n) for(int i = 0; i < (int)n; ++i)
#define FOR(i, a, b) for(int i = a; i < (int)b; ++i)
#define rrep(i, n) for(int i = ((int)n - 1); i >= 0; --i)

typedef long long ll;
typedef long double ld;

const int Inf = 1e9;
const double EPS = 1e-9;
const int MOD = 1e9 + 7;

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

int w, h;
vector<string> s;
vector<vector<int> > g;

void bfs(int sx, int sy, int color) {
    g[sx][sy] = color;
    rep (i, 4) {
        int nx, ny;
        nx = sx + dx[i], ny = sy + dy[i];
        if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
        if (s[nx][ny] == '#') continue;
        if (g[nx][ny] != 0) continue; 
        bfs(nx, ny, color);
    }
}

int bfs(int sx, int sy) {
    vector<vector<int> > dist(h, vector<int>(w, Inf));
    queue<pair<int, int> > q;
    q.push(make_pair(sx, sy));
    dist[sx][sy] = 0;
    while (!q.empty()) {
        int x = q.front().first, y = q.front().second;
        q.pop();
        rep (i, 4) {
            int nx, ny;
            nx = x + dx[i], ny = y + dy[i];
            if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
            if (dist[nx][ny] != Inf) continue;
            if (g[nx][ny] == 2) return dist[x][y];
            dist[nx][ny] = dist[x][y] + 1;
            q.push(make_pair(nx, ny));
        }
    }
    return Inf;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(0);
    cin >> w >> h;
    s = vector<string>(h);
    g = vector<vector<int> >(h, vector<int>(w, 0));
    rep (i, h) cin >> s[i];
    int color = 1;
    rep (i, h) {
        rep (j, w) {
            if (s[i][j] == '.' && g[i][j] == 0) {
                bfs(i, j, color);
                color++;
            }
        }
    }
    int res = Inf;
    rep (i, h) {
        rep (j, w) {
            if (g[i][j] == 1) res = min(res, bfs(i, j));
        }
    }
    cout << res << endl;
    
    return 0;
}
0