본문 바로가기

PS

백준 BOJ 2667 C++ DFS [단지번호붙이기]

// 깊이 우선 탐색(DFS)을 이용한 풀이
#include <bits/stdc++.h>
using namespace std;

int n, board[30][30];
bool visited[30][30];
vector<int> ans;

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

int dfs(int x, int y) {
    visited[x][y] = true;
    int cnt = 1;  // 시작 노드 카운트
    for (int k = 0; k < 4; ++k) {
        int nx = x + dx[k];
        int ny = y + dy[k];
        if (nx >= 0 && nx < n && ny >= 0 && ny < n) {
            if (board[nx][ny] == 1 && !visited[nx][ny]) {
                cnt += dfs(nx, ny);
            }
        }
    }
    return cnt;  // 합산된 노드 카운트 반환
}

void solve() {
    cin >> n;
    for (int i = 0; i < n; ++i) {
        string row;
        cin >> row;
        for (int j = 0; j < n; ++j) {
            board[i][j] = row[j] - '0';
        }
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (board[i][j] == 1 && !visited[i][j]) {
                ans.push_back(dfs(i, j));
            }
        }
    }
    sort(ans.begin(), ans.end());
    cout << ans.size() << '\n';
    for (auto elem : ans) {
        cout << elem << '\n';
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    solve();
    return 0;
}