PS

BOJ 2667 : 단지번호붙이기

lickelon 2024. 2. 5. 23:16
  • 문제 링크 : boj.kr/2667
  • 난이도 : S1
  • 태그 : DFS, BFS
 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net


코드

#include <bits/stdc++.h>

#define all(x) (x).begin(), (x).end()

#define INF 0x7FFFFFFF

using namespace std;

using ll = long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll, ll>;

int board[27][27];

int dfs(int x, int y) {
    stack<pii> _st;
    _st.push({x, y});
    board[x][y] = 0;

    int cnt = 0;
    while(!_st.empty()) {
        cnt++;
        pii curr = _st.top(); _st.pop();
        int cx = curr.first, cy = curr.second;
        int dx[] = {1,0,-1,0};
        int dy[] = {0,1,0,-1};
        for(int i = 0; i < 4; i++) {
            if(board[cx+dx[i]][cy+dy[i]]) {
                _st.push({cx+dx[i], cy+dy[i]});
                board[cx+dx[i]][cy+dy[i]] = 0;
            }
        }
    }
    return cnt;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int n;
    cin >> n;
    for(int i = 0; i < n; i++) {
        string s;
        cin >> s;
        for(int j = 0; j < n; j++) {
            board[i+1][j+1] = s[j] - '0';
        }
    }

    vector<int> result;
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            if(board[i][j] == 1) {
                result.emplace_back(dfs(i, j));
            }
        }
    }
    sort(all(result));
    
    cout << result.size() << "\n";
    for(auto u : result) {
        cout << u << "\n";
    }

    return 0;
}

풀이

연결되었다는 것을 파악하기 위해 DFS 또는 BFS를 적절히 이용해준다.

문제 자체는 그래프 탐색 기본 문제 수준이라 어렵지 않다.

'PS' 카테고리의 다른 글

BOJ 9575 : 행운의 수  (1) 2024.02.08
BOJ 25344 : 행성 정렬  (2) 2024.02.07
BOJ 26259 : 백룸  (0) 2024.02.06
BOJ 20921 : 그렇고 그런 사이  (1) 2024.02.04
BOJ 4307 : 개미  (0) 2024.02.03