내 풀이
#include <bits/stdc++.h>
using namespace std;
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int n;
string board[27];
int vis[27][27];
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for(int i = 0; i < n; i++) {
cin >> board[i];
}
int cnt=0;
vector<int> v;
queue<pair<int,int>> q;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(board[i][j]=='1'&&vis[i][j]==0)
{
vis[i][j]=1;
int width=1;
q.push({i,j});
cnt++;
while(!q.empty())
{
int x=q.front().first;
int y=q.front().second;
q.pop();
for(int i=0;i<4;i++)
{
int nx=x+dx[i];
int ny=y+dy[i];
if(nx<0||nx>=n||ny<0||ny>=n)continue;
if(board[nx][ny]=='0'||vis[nx][ny]==1)continue;
vis[nx][ny]=1;
width++;
q.push({nx,ny});
}
}
v.push_back(width);
}
}
}
sort(v.begin(),v.end());
cout<<cnt<<'\n';
for(int i:v)
cout<<i<<'\n';
return 0;
}
정답 풀이
// Authored by : 0silver00
// Co-authored by : -
// http://boj.kr/118e3a5900f94c4aae7aff09c263ef06
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int n;
string board[27];
int vis[27][27];
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for(int i = 0; i < n; i++) {
cin >> board[i];
}
int count = 0;
vector <int> ans;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == '0' || vis[i][j] == 1)
continue;
queue < pair<int, int> > Q;
vis[i][j] = 1;
Q.push({ i, j });
int width = 1;
count++;
while (!Q.empty()) {
auto cur = Q.front();
Q.pop();
for (int dir = 0; dir < 4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx < 0 || nx >= n || ny < 0 || ny >= n)
continue;
if (board[nx][ny] == '0' || vis[nx][ny] == 1)
continue;
Q.push({ nx, ny });
vis[nx][ny] = 1;
width++;
}
}
ans.push_back(width);
}
}
cout << count << '\n';
sort(ans.begin(), ans.end());
for (int i : ans)
cout << i << '\n';
return 0;
}
'Algorithm > C++' 카테고리의 다른 글
[백준 2468] 안전 영역 (0) | 2022.09.06 |
---|---|
[백준 5014] 스타트링크 (0) | 2022.09.04 |
[백준 2583] 영역 구하기 (0) | 2022.09.04 |
[백준 17298] 오큰수 (0) | 2022.09.03 |
[백준 6198] 옥상 정원 꾸미기 (0) | 2022.09.03 |
댓글