BOJ 2667 단지번호붙이기

1 개요[ | ]

BOJ 2667 단지번호붙이기


2 C++[ | ]

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

int N;
bool A[26][26] = {};
bool visited[26][26] = {};
int cnt;

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

vector<int> answer;

void bfs(int x, int y) {
    queue<pair<int,int>> q;
    q.push({x, y});
    visited[y][x] = true;
    cnt = 1;
    while(!q.empty()) {
        x = q.front().first;
        y = q.front().second;
        q.pop();
        for(int i=0; i<4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx>=0 && nx<N && ny>=0 && ny<N && A[ny][nx] && !visited[ny][nx]) {
                q.push({nx, ny});
                visited[ny][nx] = true;
                cnt++;
            }
        }
    }
}

void solve() {
    for(int i=0; i<N; i++) {
        for(int j=0; j<N; j++) {
            if(A[i][j]==1 && !visited[i][j]) {
                bfs(j, i);
                answer.push_back(cnt);
            }
        }
    }
    sort(answer.begin(), answer.end());
}

int main() {
    cin >> N;
    string temp;
    for(int i=0; i<N; i++) {
        cin >> temp;
        for(int j=0; j<N; j++) {
            A[i][j] = temp[j] - '0';
        }
	}
    solve();    
    cout << answer.size() << '\n';
    for(auto& el: answer) {
        cout << el << '\n';
    }
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}