Skip to content

Commit e31fc92

Browse files
committed
[Silver I] Title: 단지번호붙이기, Time: 112 ms, Memory: 14488 KB -BaekjoonHub
1 parent fcd6d99 commit e31fc92

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# [Silver I] 단지번호붙이기 - 2667
2+
3+
[문제 링크](https://www.acmicpc.net/problem/2667)
4+
5+
### 성능 요약
6+
7+
메모리: 14488 KB, 시간: 112 ms
8+
9+
### 분류
10+
11+
그래프 이론, 그래프 탐색, 너비 우선 탐색, 깊이 우선 탐색, 격자 그래프, 플러드 필
12+
13+
### 제출 일자
14+
15+
2025년 8월 1일 15:54:57
16+
17+
### 문제 설명
18+
19+
<p><그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.</p>
20+
21+
<p style="text-align: center;"><img alt="" src="https://www.acmicpc.net/upload/images/ITVH9w1Gf6eCRdThfkegBUSOKd.png" style="height:192px; width:409px"></p>
22+
23+
### 입력
24+
25+
<p>첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.</p>
26+
27+
### 출력
28+
29+
<p>첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.</p>
30+
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
static int[][] houseMap;
6+
static boolean[][] visited;
7+
static int sum, N;
8+
static List<Integer> houseCnt = new ArrayList<>();
9+
static int[] dx = {0,0,-1,1};
10+
static int[] dy = {-1,1,0,0};
11+
12+
13+
public static void main(String[] args) throws IOException{
14+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15+
N = Integer.parseInt(br.readLine());
16+
houseMap = new int[N][N];
17+
visited = new boolean[N][N];
18+
19+
for(int i=0; i<N; i++){
20+
String[] s = br.readLine().split("");
21+
for(int j=0; j<N; j++){
22+
if(Integer.parseInt(s[j]) == 1) houseMap[i][j] = 1;
23+
}
24+
}
25+
26+
for(int i=0; i<N; i++){
27+
for(int j=0; j<N; j++){
28+
if(!visited[i][j] && houseMap[i][j] == 1){
29+
sum=0; //단지 시작할때 sum 초기화
30+
dfs(i,j);
31+
houseCnt.add(sum);
32+
}
33+
}
34+
}
35+
36+
Collections.sort(houseCnt);
37+
System.out.println(houseCnt.size()); //단지수 출력
38+
for(int cnt : houseCnt){
39+
System.out.println(cnt); //단지당 집 갯수 출력
40+
}
41+
}
42+
43+
public static void dfs(int x, int y){
44+
visited[x][y] = true;
45+
sum++;
46+
47+
for(int i=0; i<4; i++){
48+
int newX = x+dx[i];
49+
int newY = y+dy[i];
50+
51+
// 경계 체크
52+
if(newX >= 0 && newX < N && newY >= 0 && newY < N){
53+
if(!visited[newX][newY] && houseMap[newX][newY] == 1){
54+
dfs(newX, newY);
55+
}
56+
}
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)