ZJANS

b701. 我的領土有多大

Medium Last Update: 2026/01/20
BFS

解法一、BFS

✅ 完整代碼

評分結果(參考) : AC (1ms, 336KB)

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

int x, y;

void bfs(int i, int j, vector<vector<int>>& v){
    int w=x, n=y, e=0, s=0, area=0;

    queue<pair<int, int>> q;
    q.push({i, j});
    v[i][j] = 0;
    
    while(!q.empty()){
        int a = q.front().first;
        int b = q.front().second;
        q.pop();
        
        w = min(w, b);
        n = min(n, a);
        e = max(e, b);
        s = max(s, a);
        area++;
        
        if(a+1<x  && v[a+1][b]){ q.push({a+1, b}); v[a+1][b]=0; }
        if(a-1>=0 && v[a-1][b]){ q.push({a-1, b}); v[a-1][b]=0; }
        if(b+1<y  && v[a][b+1]){ q.push({a, b+1}); v[a][b+1]=0; }
        if(b-1>=0 && v[a][b-1]){ q.push({a, b-1}); v[a][b-1]=0; }
    }
    
    cout << w << " "
         << n << " "
         << e << " "
         << s << " "
         << area << "\n";
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    cin >> x >> y;
    vector<vector<int>> v(x, vector<int>(y));
    for(int i=0; i<x; i++){
        for(int j=0; j<y; j++){
            cin >> v[i][j];
        }
    }
    
    for(int i=0; i<x; i++){
        for(int j=0; j<y; j++){
            if(v[i][j]) bfs(i, j, v);
        }
    }
    
    return 0;
}