Hamutaro - Hamtaro 4

Algorithm/BOJ

[Silver I/JAVA] 2667 ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ

carsumin 2024. 12. 13. 21:09

https://www.acmicpc.net/problem/2667

 

 

ํ’€์ด
  • ์ด์ „์— ํ’€์—ˆ๋˜ ์˜์—ญ๊ตฌํ•˜๊ธฐ์™€ ์œ ์‚ฌํ•œ ๋ฌธ์ œ๋‹ค. (https://marginata.tistory.com/173)
  • ์˜์—ญ๊ตฌํ•˜๊ธฐ๊ฐ€ ์ƒ‰์น ๋˜์ง€ ์•Š์€ ์˜์—ญ์˜ ๋„“์ด๋ฅผ ๊ตฌํ•œ๊ฒƒ์ด๋ผ๋ฉด ๋ฐ˜๋Œ€๋กœ ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ๋Š” ์ง‘์ด ์žˆ๋Š”๊ณณ์˜ ๋„“์ด๋ฅผ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.
  • ์ฃผ์˜ํ•  ์ ์€ 0001010 ์ด๋Ÿฐ์‹์œผ๋กœ ๊ณต๋ฐฑ์—†์ด ์ž…๋ ฅ์„ ๋ฐ›๊ธฐ ๋•Œ๋ฌธ์— charAt()์„ ์ด์šฉํ•ด์„œ ํ•œ์ž๋ฆฌ์”ฉ charํ˜•์œผ๋กœ ์ถ”์ถœํ•œ ๋’ค์— ์ •์ˆ˜ํ˜•์œผ๋กœ ๋ณ€ํ™˜ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

 

์ „์ฒด ์ฝ”๋“œ
import java.io.*;
import java.util.*;

public class Main{
    static int[][] map; //์ง€๋„
    static int[] dx = {1,-1,0,0};
    static int[] dy = {0,0,1,-1};
    static int N; //์ง€๋„ ํฌ๊ธฐ
    static int cnt; //์ง‘์˜ ์ˆ˜
    static ArrayList<Integer> list = new ArrayList<>(); //์ง‘์˜ ์ˆ˜ ๊ฒฐ๊ณผ ์ €์žฅ
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        
        //map ํฌ๊ธฐ
        map = new int[N][N];
        
        //map ์ดˆ๊ธฐํ™”
        for(int i=0; i<N; i++){
            String str = br.readLine();
            for(int j=0; j<N; j++){
                map[i][j] = str.charAt(j) - '0';
            }
        }
        
        //DFS ํƒ์ƒ‰
        for(int x=0; x<N; x++){
            for(int y=0; y<N; y++){
                if(map[x][y]==1){
                    cnt=0;
                    dfs(x,y);
                    list.add(cnt);
                }
            }
        }
        
        //์ถœ๋ ฅ
        System.out.println(list.size());
        
        Collections.sort(list);
        for(Integer n : list){
            System.out.println(n);
        }
    }
    
    //DFS ํƒ์ƒ‰
    private static void dfs(int x, int y){
        map[x][y]=0; //์ง‘์ด ์—†์œผ๋ฉด
        cnt++;
        
        for(int i=0; i<4; i++){
            int nx = x+dx[i];
            int ny = y+dy[i];

            if(nx>=0 && nx<N && ny>=0 && ny<N){
                if(map[nx][ny]==1){ //์ง‘์ด ์žˆ์œผ๋ฉด ํƒ์ƒ‰ ๊ณ„์†
                    dfs(nx, ny);                        
                }
            }
        }
    }
}