https://www.acmicpc.net/problem/2667
제출 코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
string arr[26];
int dx[4] = { 1, -1, 0, 0 };
int dy[4] = { 0, 0, 1, -1 };
int dfs(int x, int y)
{
// 배열 범위를 초과하거나 0일 경우 리턴값 0
if (x < 0 || x >= n || y < 0 || y >= n || arr[x][y] == '0')
return 0;
arr[x][y] = '0';
int cnt = 1;
// 인자로 들어온 좌표의 상하좌우를 체크해서 cnt 세기
for (int i = 0; i < 4; i++)
cnt += dfs(x + dx[i], y + dy[i]);
return cnt;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i = 0; i < n; i++)
cin >> arr[i];
vector<int> v;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] == '1')
v.push_back(dfs(i, j));
cout << v.size() << '\n';
sort(v.begin(), v.end());
for (auto& res : v)
cout << res << '\n';
}
'Programing > 백준, 프로그래머스(C++)' 카테고리의 다른 글
[C++][백준 11724] 연결 요소의 개수 (DFS, BFS) (0) | 2025.01.31 |
---|---|
[C++][백준 11660] 구간 합 구하기 5 (0) | 2025.01.30 |
[C++][백준 14929] 귀찮아(SIB) (0) | 2025.01.28 |
[C++][백준 3474] 교수가 된 현우 (0) | 2025.01.28 |
[C++][백준 21920] 서로소 평균 (0) | 2025.01.27 |