[JAVA-자바] 2667번: 단지번호붙이기

2025. 3. 31. 03:50·알고리즘/백준

 

소스코드:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Main {
    static BufferedReader br;
    static BufferedWriter bw;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int[] dx = new int[]{0, 0, -1, 1};
        int[] dy = new int[]{-1, 1, 0, 0};

        int width = Integer.parseInt(br.readLine());
        int height = width;

        boolean[][] visited = new boolean[height + 2][width + 2];
        boolean[][] board = new boolean[height + 2][width + 2];

        for (int y = 1; y <= height; y++) {
            String line = br.readLine();
            for (int x = 1; x <= width; x++) {
                board[y][x] = line.charAt(x - 1) == '1';
            }
        }
        br.close();

        List<Integer> list = new ArrayList<>();

        for (int y = 1; y <= height; y++) {
            for (int x = 1; x <= width; x++) {
                if (!board[y][x] || visited[y][x]) {
                    continue;
                }
                // solve
                int total = 0;
                Queue<int[]> queue = new LinkedList<>();
                queue.add(new int[]{x, y});
                visited[y][x] = true;

                while (!queue.isEmpty()) {
                    int[] current = queue.poll();
                    int xx = current[0];
                    int yy = current[1];
                    total++;

                    for (int i = 0; i < 4; i++) {
                        int calcX = xx + dx[i];
                        int calcY = yy + dy[i];
                        if (!visited[calcY][calcX] && board[calcY][calcX]) {
                            visited[calcY][calcX] = true;
                            queue.add(new int[]{calcX, calcY});
                        }
                    }
                }
                list.add(total);
            }
        }

        Collections.sort(list);
        bw.write(list.size() + "\n");
        for (Integer item : list) {
            bw.write(item + "\n");
        }
        bw.close();
    }
}

 

글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.

여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.

'알고리즘 > 백준' 카테고리의 다른 글

[JAVA-자바] 5525번: IOIOI  (0) 2025.04.01
[JAVA-자바] 11403번: 경로 찾기  (0) 2025.04.01
[JAVA-자바] 2178번: 미로 탐색  (0) 2025.03.28
[JAVA-자바] 21736번: 헌내기는 친구가 필요해  (0) 2025.03.27
[JAVA-자바] 18111번: 마인크래프트  (0) 2025.03.26
'알고리즘/백준' 카테고리의 다른 글
  • [JAVA-자바] 5525번: IOIOI
  • [JAVA-자바] 11403번: 경로 찾기
  • [JAVA-자바] 2178번: 미로 탐색
  • [JAVA-자바] 21736번: 헌내기는 친구가 필요해
raven
raven
Github : https://github.com/RabeMaster | Email : ra___be@naver.com
  • raven
    배움을 원하는 사람
    raven
  • 전체
    오늘
    어제
  • 공지사항

    • 안녕하세요
    • 분류 전체보기 (169)
      • 네이버 부스트캠프 10기 (7)
        • 멤버십 (5)
        • 챌린지 (1)
        • 베이직 (1)
      • 공부 (2)
        • JAVA (1)
        • CS (0)
        • 정보처리기사 (1)
      • 알고리즘 (159)
        • 백준 (159)
      • 개발 (1)
        • 백준 확장 프로그램 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 인기 글

  • 태그

    개발
    IT
    자료 구조
    멤버십
    네이버
    스택
    다이나믹 프로그래밍
    백트래킹
    java
    정렬
    부스트캠프
    코딩테스트
    그래프 이론
    네부캠
    코딩
    백준
    알고리즘
    네이버부스트캠프
    회고
    구현
    부트캠프
    너비 우선 탐색
    문자열
    그리디 알고리즘
    그래프 탐색
    코테
    최단 경로
    수학
    브루트포스 알고리즘
    자바
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
raven
[JAVA-자바] 2667번: 단지번호붙이기
상단으로

티스토리툴바