풀이전략
- 인접한 것들끼리의 숫자를 세야 한다.
- 인접한 것 벗어나면 0으로 초기화
- dfs로 접근해야 쉽게 풀린다.
- dfs에서의 예외처리를 주의하자.
소스코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
int arr[25][25];
int dx[] = { 0,0,-1,1 };
int dy[] = { -1,1,0,0 };
void dfs(int y, int x, int &cnt)
{
if (0 > y || y >= n || 0 > x || x >= n)
return;
if (arr[y][x] == 0)
return;
cnt++;
arr[y][x] = 0;
dfs(y, x + 1, cnt);
dfs(y, x - 1, cnt);
dfs(y + 1, x, cnt);
dfs(y - 1, x, cnt);
}
int main() {
vector<int>v;
cin>> n;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%1d", &arr[i][j]);
}
}
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (arr[i][j] == 1)
{
dfs(i, j, cnt);
v.push_back(cnt);
cnt = 0;
}
}
}
cout << v.size() << "\n";
sort(v.begin(), v.end());
for (auto i : v)
cout << i << "\n";
return 0;
}