알고리즘/DFS, BFS
단지번호 붙이기
SW1
2019. 11. 15. 18:57
문제
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.
입력
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.
출력
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.
import java.util.*;
class Main {
static int n; // 지도의 크기
static int[][] board; // 지도 배열
static int[] dx = { 1, 0, -1, 0 };
static int[] dy = { 0, 1, 0, -1 };
static int complex_num = 2; // 처음 시작 단지번호, 2를 시작으로 한 이유는 1이 지도 내 집 여부를 확인하는 숫자이기 때문
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
board = new int[n][n];
for (int i = 0; i < n; i++) {
String str = scan.next();
for (int j = 0; j < n; j++) {
board[i][j] = str.charAt(j) - '0';
}
}
while (find() != null) { // 더 이상 지도에 집이 없을때까지 탐색
bfs(find().x, find().y);
}
ArrayList<Integer> list = new ArrayList<Integer>(); // 단지수를 담는 리스트
for (int i = 2; i < complex_num; i++) {
int cnt = 0;
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (board[j][k] == i)
cnt++;
}
}
list.add(cnt);
}
Collections.sort(list); // 단지수 오름차순 정렬
System.out.println(complex_num - 2); // 시작이 2였고 끝날때 한번 더 더해지므로 2를 빼줌
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
static Dot find() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 1) {
return new Dot(i, j);
}
}
}
return null;
}
static void bfs(int x, int y) { // bfs
Queue<Dot> q = new LinkedList<Dot>();
q.add(new Dot(x, y));
while (!q.isEmpty()) {
Dot d = q.poll();
board[d.x][d.y] = complex_num;
for (int i = 0; i < 4; i++) {
int next_x = d.x + dx[i];
int next_y = d.y + dy[i];
if (next_x < 0 || next_y < 0 || next_x >= n || next_y >= n || board[next_x][next_y] != 1)
continue;
q.add(new Dot(next_x, next_y));
board[next_x][next_y] = complex_num;
}
}
complex_num++; // 같은 단지 집 탐색이 끝나면 번호 1 증가
}
}
class Dot {
int x;
int y;
Dot(int x, int y) {
this.x = x;
this.y = y;
}
}