[Algorithm /백준] 단지번호붙이기
2023. 11. 13. 15:01ㆍAlgorithm/JAVA
[문제]
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.
[입력]
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.
[출력]
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.
[문제해결 - BFS]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
static boolean[][] visited;
static int count = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Main ma = new Main();
int num = Integer.parseInt(br.readLine());
int[][] arr = new int[num][num];
visited = new boolean [num][num];
List<Integer> list = new ArrayList<Integer>();
//Line을 통해 입력받아 charAt으로 넣기
for (int i = 0; i < num; i++) {
String row = br.readLine();
for (int j = 0; j < num; j++) {
arr[i][j] = Character.getNumericValue(row.charAt(j));
}
}
br.close();
//BFS를 통해 인접행렬 체크
for(int i = 0 ; i<arr.length; i++) {
for(int j = 0 ; j<arr.length; j++) {
if(!visited[i][j]&& arr[i][j] == 1) {
//인접행렬이 체크되기전 count를 0으로 초기화
count= 0;
ma.BFS(arr, i, j);
list.add(count);
}
}
}
//군집 정렬
Collections.sort(list);
//총 군집 갯수 출력
System.out.println(list.size());
//군집의 숫자 list출력
for(int i = 0 ; i < list.size() ;i++) {
System.out.println(list.get(i));
}
}
public void BFS(int[][] arr, int i, int j) {
//방문 true
visited[i][j] = true;
count++;
//인접행렬을 찾아서 체크
if(i-1 >=0 && !visited[i-1][j] && arr[i-1][j]==1) {
BFS(arr,i-1,j);
}
if(i+1 < arr.length && !visited[i+1][j]&& arr[i+1][j]==1) {
BFS(arr,i+1,j);
}
if(j-1 >=0 && !visited[i][j-1] && arr[i][j-1]==1) {
BFS(arr,i,j-1);
}
if(j+1 < arr.length && !visited[i][j+1]&& arr[i][j+1]==1) {
BFS(arr,i,j+1);
}
}
}
'Algorithm > JAVA' 카테고리의 다른 글
[Algorithm /백준] 미로탐색 (0) | 2023.11.15 |
---|---|
[Algorithm /백준] 연결 요소의 개수 (0) | 2023.11.15 |
[Algorithm /백준] 바이러스 (0) | 2023.11.13 |
[Algorithm /프로그래머스] 가장 큰 수 (0) | 2023.11.11 |
[Algorithm /프로그래머스] 귤 고르기 (0) | 2023.11.10 |