DFS/BFS 백준 알고리즘 자바 2667 ‘단지번호붙이기’

1 minute read

Problem

정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.

Input
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.

Output
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.

Solution

scan.nextInt()를 또 사용할 수 없는 입력값이었다! scan.nextLine().trim().toCharArray(), Character.getNumericValue() 외워두자! 참고로 nextInt()이후 엔터값 처리를 위해 nextLine()을 배열 값을 읽기 전에 사용했다.

주변에 붙어있는 값들만 읽어 해결하는 문제라서 BFS를 적용했다. 일전에 다른 문제와 비슷하다. 다만, 출력값이 두개인데 우선 더해진 집들의 수를 카운트해서 리턴해주고, 그것을 리스트에 담아서 ‘리스트 수 = 단지수’, ‘리스트값 = 집 개수’로 해결! 문제 조건 ‘정렬하여’를 놓치는 실수를 하지 말자!

Code

import java.util.Collections;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Main {
	static boolean[][] v;
	static int n;
	static Queue qi = new LinkedList<>();
	static Queue qj = new LinkedList<>();
	public static int bfs(int[][] houses) {
		int[] di = {0, 0, 1, -1}, dj = {1, -1, 0, 0};
		int i, j, _i, _j, cnt = 0;
		
		while(!qi.isEmpty()) {
			i = qi.poll(); j = qj.poll();
			cnt++;
			v[i][j] = true;
			
			for(int idx = 0; idx < 4; idx++) {
				_i = i + di[idx]; _j = j + dj[idx];
				
				if(_i < 0 || _j < 0 || _i >= n || _j >= n) continue;
				if(houses[_i][_j] == 1 && !v[_i][_j]) {
					qi.add(_i); qj.add(_j);
					v[_i][_j] = true;
				}
			}
		}
		return cnt;
	}
	
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		n = scan.nextInt(); scan.nextLine();
		v = new boolean[n][n];
		int[][] houses = new int[n][n];
		List cntList = new ArrayList<>();
		
		for(int i = 0; i < n; i++) {
			char[] tmp = scan.nextLine().trim().toCharArray();
			for(int j = 0; j < n; j++)
				houses[i][j] = Character.getNumericValue(tmp[j]); 
		}
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				if(houses[i][j] == 1 && !v[i][j]) {
					qi.add(i); qj.add(j);
					cntList.add(bfs(houses));
				}
			}
		}
		System.out.println(cntList.size());
        Collections.sort(cntList);
		cntList.forEach(System.out::println);
	}
}

Tags:

Updated: