단지번호붙이기 2667

PublicMinsu·2022년 12월 29일
0

문제

접근 방법

BFS, DFS 둘 다 사용가능하다. 정석적인 문제이다. 아마도 보통 DFS를 주로 사용할 것이다. 1인 곳을 탐색하여 기록해주면 된다.

코드

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int N;
    cin >> N;
    vector<vector<int>> map(N, vector<int>(N));
    vector<int> answer;
    queue<pair<int, int>> bfs;
    for (int i = 0; i < N; ++i)
    {
        string num;
        cin >> num;
        for (int j = 0; j < N; ++j)
        {
            map[i][j] = num[j] - '0';
        }
    }
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
        {
            if (!map[i][j])
                continue;
            bfs.push({i, j});
            int sum = 1;
            map[i][j] = 0;
            while (!bfs.empty())
            {
                auto cur = bfs.front();
                bfs.pop();
                for (int i = 0; i < 4; ++i)
                {
                    pair<int, int> next = {cur.first + dx[i], cur.second + dy[i]};
                    if (next.first < 0 || next.second < 0 || next.first >= N || next.second >= N)
                        continue;
                    if (map[next.first][next.second])
                    {
                        ++sum;
                        map[next.first][next.second] = 0;
                        bfs.push(next);
                    }
                }
            }
            if (sum)
                answer.push_back(sum);
        }
    sort(answer.begin(), answer.end());
    cout << answer.size() << "\n";
    for (int i : answer)
    {
        cout << i << "\n";
    }
    return 0;
}

풀이

0인 곳은 건너뛰고 1인 곳만을 탐색하여서 기록해주면 된다.
지도를 받을 때 int와 같은 정수형으로 받으면 안 된다. 25의 크기이므로 자라는 수의 단위까지 간다.
string으로 받아서 처리해줘야 한다.

profile
연락 : publicminsu@naver.com

0개의 댓글