結果

問題 No.13 囲みたい!
ユーザー Mister
提出日時 2020-08-19 20:14:33
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 4 ms / 5,000 ms
コード長 1,373 bytes
コンパイル時間 1,027 ms
コンパイル使用メモリ 91,812 KB
最終ジャッジ日時 2025-01-13 03:57:20
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <functional>

template <class T>
std::vector<T> vec(int len, T elem) { return std::vector<T>(len, elem); }

const std::vector<std::pair<int, int>> dxys{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

void solve() {
    int h, w;
    std::cin >> w >> h;

    auto grid = vec(h, vec(w, 0));
    for (auto& v : grid) {
        for (auto& x : v) std::cin >> x;
    }

    auto visited = vec(h, vec(w, 0));

    std::function<void(int, int, int, int)> dfs =
        [&](int x, int y, int px, int py) {
            visited[x][y] = 2;

            for (auto [dx, dy] : dxys) {
                int nx = x + dx, ny = y + dy;
                if (nx < 0 || h <= nx ||
                    ny < 0 || w <= ny ||
                    (nx == px && ny == py) ||
                    grid[nx][ny] != grid[x][y]) continue;

                if (visited[nx][ny] == 2) {
                    std::cout << "possible\n";
                    std::exit(0);
                }
                dfs(nx, ny, x, y);
            }

            visited[x][y] = 1;
        };

    for (int sx = 0; sx < h; ++sx) {
        for (int sy = 0; sy < w; ++sy) {
            if (visited[sx][sy] == 0) dfs(sx, sy, -1, -1);
        }
    }

    std::cout << "impossible\n";
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);

    solve();

    return 0;
}
0