https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
이 문제는 DFS를 사용하고, 영역 검사를 하면 해결할 수 있다.
#include <iostream>
#include <cstring>
#include <vector>
#include<algorithm>
using namespace std;
int visited[26][26];
int dx[] = { 0,0,-1,1 };
int dy[] = { -1,1,0,0 };
vector<int> v;
int N, counter = 0, cnt=0;
char graph[26][26];
void dfs(int x,int y) {
visited[x][y] = 1;
cnt++;
for (int i = 0; i < 4; i++) {
int ux = x + dx[i], uy = y + dy[i];
if (ux < 0 || uy < 0 || ux >= N || uy >= N) continue;
if (graph[ux][uy] == '0') continue;
if (!visited[ux][uy] && graph[ux][uy] == '1') {
dfs(ux, uy);
}
}
}
int main() {
cin >> N;
memset(graph, '0', sizeof(graph));
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> graph[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j] && graph[i][j] == '1') {
cnt = 0;
dfs(i, j);
counter++;
v.push_back(cnt);
}
}
}
cout << counter << '\n';
sort(v.begin(), v.end());
for (int i = 0; i < v.size(); i++)
cout << v[i] << '\n';
}
'Baekjoon Review' 카테고리의 다른 글
[Silver 3] 1463번 1로 만들기 (0) | 2023.11.02 |
---|---|
[Silver 1] 2178번 미로 탐색 (0) | 2023.11.02 |
[Silver 2] 16953번 A -> B (0) | 2023.11.01 |
[Gold 5] 10026번 적록색약 (0) | 2023.11.01 |
[Gold 5] 7569번 토마토 (0) | 2023.10.26 |