728x90
문제
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.
입력
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.
출력
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.
연결요소 찾기 문제다. 연결요소별로 몇 개의 요소가 포함되는지 구분해야 하므로, 각각의 연결요소 집합에 대해 고유한 id를 부여한다.
class Graph
{
private:
int size_;
vector<vector<int>> map_;
vector<vector<int>> visited_;
vector<int> component_size_;
const int dr_[4] = {1, -1, 0, 0};
const int dc_[4] = {0, 0, 1, -1};
public:
Graph(int n);
void setMap();
void dfs(int i, int j, int id, int &size);
vector<int> findConnectedComponent();
};
Graph::Graph(int n) : size_(n)
{
map_.resize(n, vector<int>(n, 0));
visited_.resize(n, vector<int>(n, 0));
}
void Graph::setMap()
{
for (vector<int> &row : map_)
{
string input;
cin >> input;
for (int i = 0; i < size_; i++)
row[i] = input[i] - '0';
}
}
void Graph::dfs(int i, int j, int id, int &size)
{
visited_[i][j] = id; // 현재 집을 현재 연결 요소로 추가
size++; // 연결 요소의 개수 추가
for (int d = 0; d < 4; d++)
{
int nr = i + dr_[d];
int nc = j + dc_[d];
if (nr >= 0 && nr < size_ && nc >= 0 && nc < size_ && map_[nr][nc] == 1 && !visited_[nr][nc])
dfs(nr, nc, id, size);
}
}
vector<int> Graph::findConnectedComponent()
{
int id = 0; // 현재 연결 요소의 번호
for (int i = 0; i < size_; i++)
{
for (int j = 0; j < size_; j++)
{
// map_ 값이 1이면 방문하지 않은 집
if (map_[i][j] == 1 && !visited_[i][j])
{
id++;
int size = 0; // 현재 연결 요소의 크기
dfs(i, j, id, size);
component_size_.push_back(size);
}
}
}
return component_size_;
}
component_size_ 벡터는 연결요소 집합을 인덱스로 포함되는 요소의 개수를 저장한다. dfs가 종료되는 시점이 하나의 연결요소 집합 탐색이 끝나는 때이므로 findConnectedComponent 함수에서 dfs가 반환되면 size는 요소의 개수가 된다.
int main()
{
// freopen("input.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin >> N;
Graph g(N);
g.setMap();
vector<int> component_size = g.findConnectedComponent();
sort(component_size.begin(), component_size.end());
cout << component_size.size() << '\n'; // 연결 요소의 개수
for (int size : component_size)
cout << size << '\n'; // 연결 요소의 크기
return 0;
}
전체 코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Graph
{
private:
int size_;
vector<vector<int>> map_;
vector<vector<int>> visited_;
vector<int> component_size_;
const int dr_[4] = {1, -1, 0, 0};
const int dc_[4] = {0, 0, 1, -1};
public:
Graph(int n);
void setMap();
void dfs(int i, int j, int id, int &size);
vector<int> findConnectedComponent();
};
Graph::Graph(int n) : size_(n)
{
map_.resize(n, vector<int>(n, 0));
visited_.resize(n, vector<int>(n, 0));
}
void Graph::setMap()
{
for (vector<int> &row : map_)
{
string input;
cin >> input;
for (int i = 0; i < size_; i++)
row[i] = input[i] - '0';
}
}
void Graph::dfs(int i, int j, int id, int &size)
{
visited_[i][j] = id; // 현재 집을 현재 연결 요소로 추가
size++; // 연결 요소의 개수 추가
for (int d = 0; d < 4; d++)
{
int nr = i + dr_[d];
int nc = j + dc_[d];
if (nr >= 0 && nr < size_ && nc >= 0 && nc < size_ && map_[nr][nc] == 1 && !visited_[nr][nc])
dfs(nr, nc, id, size);
}
}
vector<int> Graph::findConnectedComponent()
{
int id = 0; // 현재 연결 요소의 번호
for (int i = 0; i < size_; i++)
{
for (int j = 0; j < size_; j++)
{
// map_ 값이 1이면 방문하지 않은 집
if (map_[i][j] == 1 && !visited_[i][j])
{
id++;
int size = 0; // 현재 연결 요소의 크기
dfs(i, j, id, size);
component_size_.push_back(size);
}
}
}
return component_size_;
}
int main()
{
// freopen("input.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin >> N;
Graph g(N);
g.setMap();
vector<int> component_size = g.findConnectedComponent();
sort(component_size.begin(), component_size.end());
cout << component_size.size() << '\n'; // 연결 요소의 개수
for (int size : component_size)
cout << size << '\n'; // 연결 요소의 크기
return 0;
}
728x90
'Baekjoon' 카테고리의 다른 글
[Baekjoon] 6064: 카잉 달력 - (C3, S1) Brute Force (0) | 2025.01.24 |
---|---|
[Baekjoon] 5525: IOIOI - (C3, S1) 문자열 (0) | 2025.01.24 |
[Baekjoon] 2178: 미로탐색 - (C3, S1) BFS (0) | 2025.01.21 |
[Baekjoon] 1697: 숨바꼭질 - (C3, S1) BFS (0) | 2025.01.20 |
[Baekjoon] 1389: 케빈 베이컨의 6단계 법칙 - (C3, S1) BFS (0) | 2025.01.20 |