반응형
문제 링크 : https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. �
www.acmicpc.net

> 풀이
BFS를 사용합시다
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
vector<int> result;
char arr[26][26];
bool visited[26][26];
int n;
int cnt;
int main(void) {
scanf("%d", &n);
getchar();
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
scanf("%c", &arr[i][j]);
getchar();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == '1' && visited[i][j] == false) {
queue<pair<int, int>> bfs;
int check = 0;
cnt++;
bfs.push({i, j});
while (!bfs.empty()) {
auto q = bfs.front();
bfs.pop();
if (visited[q.first][q.second] == true) continue;
else {
check ++, visited[q.first][q.second] = true;
}
if (arr[q.first + 1][q.second] == '1') bfs.push({q.first + 1, q.second});
if (arr[q.first][q.second + 1] == '1') bfs.push({q.first, q.second + 1});
if (q.first > 0 && arr[q.first - 1][q.second] == '1') bfs.push({q.first - 1, q.second});
if (q.second > 0 && arr[q.first][q.second - 1] == '1') bfs.push({q.first, q.second - 1});
}
if (check > 0) result.push_back(check);
}
}
}
sort(result.begin(), result.end());
printf("%d\n", cnt);
for (int i = 0; i < result.size(); i++)
printf("%d\n", result[i]);
return 0;
}
반응형
'알고리즘 (백준) > BOJ 길라잡이 (1)' 카테고리의 다른 글
| 백준 2178 (미로 탐색) / C++ (0) | 2020.07.22 |
|---|---|
| 백준 1697 (숨바꼭질) / C++ (0) | 2020.07.22 |
| 백준 1260 (DFS와 BFS) / C++ (0) | 2020.07.21 |
| 백준 1016 (제곱 ㄴㄴ 수) / C++ (0) | 2020.07.20 |
| 백준 6588 (골드바흐의 추측) / C++ (0) | 2020.07.20 |