슈콩

[BOJ] 2667 단지번호붙이기 본문

Algorithms/Baekjoon

[BOJ] 2667 단지번호붙이기

shukong 2025. 11. 27. 23:44

 

 

[문제]

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

 

 

[소스 코드]

import java.io.*;
import java.util.*;

public class Main {
	static int[] dr = {-1,1,0,0};
	static int[] dc = {0,0,-1,1};
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int[][] map = new int[n][n];
		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';
			}
		}
		List<Integer> list = new ArrayList<>();
		boolean[][] visit = new boolean[n][n];
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++) {
				if(!visit[i][j] && map[i][j]==1) {
					int cnt = 1;
					Queue<int[]> q = new LinkedList<>();
					q.offer(new int[] {i,j});
					visit[i][j] = true;
					while(!q.isEmpty()) {
						int[] curr = q.poll();
						for(int d=0;d<4;d++) {
							int nr = curr[0] + dr[d];
							int nc = curr[1] + dc[d];
							if(nr<0 || nr>=n || nc<0 || nc>=n || visit[nr][nc]) continue;
							if(map[nr][nc]==1) {
								q.offer(new int[] {nr,nc});
								visit[nr][nc] = true;
								cnt++;
							}
						}
					}
					list.add(cnt);
				}
			}
		}
		Collections.sort(list);
		System.out.println(list.size());
		for(int i : list) {
			System.out.println(i);
		}
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 7569 토마토  (0) 2025.11.28
[BOJ] 2644 촌수계산  (0) 2025.11.28
[BOJ] 2606 바이러스  (0) 2025.11.27
[BOJ] 2178 미로탐색  (0) 2025.11.27
[BOJ] 백준 1260 DFS와 BFS  (0) 2025.11.27