제출 #474824

#제출 시각아이디문제언어결과실행 시간메모리
474824dqkTracks in the Snow (BOI13_tracks)C++17
10.42 / 100
2102 ms1048576 KiB
#include <bits/stdc++.h>

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n, m;
    std::cin >> n >> m;
    std::vector<std::string> g(n);
    for (int i = 0; i < n; ++i) {
        std::cin >> g[i];
    }
    std::vector<std::vector<int>> comp(n, std::vector<int>(m, 0));
    int num = 0;
    std::function<void(int, int, char)> dfs=[&](int x, int y, char c) {
        if (x < 0 || x >= n || y < 0 || y >= m || comp[x][y] || g[x][y] != c)
            return;
        comp[x][y] = num;
        dfs(x + 1, y, c);
        dfs(x - 1, y, c);
        dfs(x, y + 1, c);
        dfs(x, y - 1, c);
    };
    g.clear();
    for (int x = 0; x < n; ++x) {
        for (int y = 0; y < m; ++y) {
            if (comp[x][y] || g[x][y] == '.')
                continue;
            num++;
            dfs(x, y, g[x][y]);
        }
    }
    std::vector<std::vector<int>> adj(num + 1);
    auto addcomp=[&](int i, int j) {
        auto add=[&](int x, int y) {
            if (x < 0 || x >= n || y < 0 || y >= m)
                return;
            if (comp[x][y] && comp[x][y] != comp[i][j]) {
                adj[comp[x][y]].push_back(comp[i][j]);
                adj[comp[i][j]].push_back(comp[x][y]);
            }
        };
        add(i - 1, j);
        add(i + 1, j);
        add(i, j + 1);
        add(i, j - 1);
    };
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (comp[i][j])
                addcomp(i, j); 
        }
    }
    comp.clear();
    std::vector<int> d(num + 1, 0);
    std::queue<int> q;
    q.push(1);
    d[1] = 1;
    int ans = 1;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : adj[u]) {
            if (d[v] == 0) {
                q.push(v);
                d[v] = d[u] + 1;
                ans = std::max(ans, d[v]);
            }
        }
    }
    std::cout << ans << "\n";
    return 0;
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...