Algorithm/백준
[백준] 2667번 단지번호붙이기
sirius
2021. 3. 11. 10:10
https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
import java.util.*;
import java.io.*;
public class Main {
// 정사각형 크기
static int N;
// 아파트
static int[][] map;
// 방문여부
static boolean[][] visit;
// 방향
static int[] dy = { 0, 1, 0, -1 };
static int[] dx = { 1, 0, -1, 0 };
// 단지번호
static int number;
// 단지별 집 카운트
static int count;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<Integer> list = new ArrayList<>();
N = Integer.parseInt(br.readLine());
map = new int[N][N];
visit = new boolean[N][N];
for (int i = 0; i < N; i++) {
String input = br.readLine();
for (int j = 0; j < N; j++) {
map[i][j] = input.charAt(j) - '0';
}
}
// 1이 집이 있는 곳
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visit[i][j] && map[i][j] == 1) {
// 단지별 집카운트 초기화
count = 0;
// 단지 번호 카운트
number++;
dfs(i, j);
list.add(count);
}
}
}
Collections.sort(list);
StringBuilder sb = new StringBuilder();
sb.append(number).append("\n");
for(int c : list) {
sb.append(c).append("\n");
}
System.out.print(sb);
}
public static void dfs(int y, int x) {
visit[y][x] = true;
// 맵에 단지 번호 부여
map[y][x] = number;
// 단지별 집 카운트
count++;
for(int i = 0; i < 4; i++) {
int ny = dy[i] + y;
int nx = dx[i] + x;
// 범위 체크
if(ny >= 0 && ny < N && nx >= 0 && nx < N) {
if(!visit[ny][nx] && map[ny][nx] == 1) {
dfs(ny, nx);
}
}
}
}
}