반응형
문제
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.
입력
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.
출력
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.
입력
7
0110100
0110101
1110101
0000111
0100000
0111110
0111000
출력
3
7
8
9
소스
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int num = Integer.parseInt(br.readLine());
int[][] board = new int[num][num];
int[] dx = {1, 0, -1, 0};
int[] dy = {0, 1, 0, -1};
for (int i = 0; i < num; i++) {
String[] rows = br.readLine().split("");
for (int j = 0; j < num; j++) {
board[i][j] = Integer.parseInt(rows[j]);
}
}
boolean[][] visited = new boolean[num][num];
ArrayList<Integer> distance = new ArrayList();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) { // i,j 시작
if (visited[i][j] || board[i][j] == 0) continue;
Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
queue.add(new Pair(i, j));
visited[i][j] = true;
int area = 0;
while (!queue.isEmpty()) {
Pair<Integer, Integer> cur = queue.peek();
queue.poll();
for (int dir = 0; dir < 4; dir++) {
int nx = cur.first + dx[dir];
int ny = cur.second + dy[dir];
if (nx < 0 || nx >= num || ny < 0 || ny >= num) continue;
if (board[nx][ny] == 0 || visited[nx][ny]) continue;
visited[nx][ny] = true;
area++;
queue.add(new Pair(nx,ny));
}
}
distance.add(area+1);
}
}
System.out.println(distance.size());
distance.stream().sorted().forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Pair<I extends Integer, I1 extends Integer> {
Integer first;
Integer second;
public Pair(Integer first, Integer second) {
this.first = first;
this.second = second;
}
public Integer first() {
return first;
}
public Integer second() {
return second;
}
}
후기
BFS/DFS 둘 다 사용가능 하지만 BFS를 이용했다.
n, m을 입력 받고 모든 좌표부터 시작하여 BFS를 돌려주면 되는데 블록에 진입했을 경우 첫 좌표부터 시작하여 area 변수를 이용하여 +1씩 더해주고 별도 ArrayList에 저장했다. 그리고 BFS로 전부 탐색이 끝나면 stream 함수를 이용해서ArrayList에 있는 값들을 오름차순으로 출력해주면 끝난다.
반응형