[JAVA-자바] 14502번: 연구소

2025. 5. 15. 23:56·알고리즘/백준

 

소스코드:

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.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;

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

    static int height, width;
    static int[][] board;
    static List<int[]> viruses;
    static int safeCount;
    static int result;

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

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

        StringTokenizer st = new StringTokenizer(br.readLine());
        height = Integer.parseInt(st.nextToken());
        width = Integer.parseInt(st.nextToken());

        board = new int[height][width];
        viruses = new ArrayList<>();
        safeCount = 0;
        result = 0;

        for (int y = 0; y < height; y++) {
            st = new StringTokenizer(br.readLine());
            for (int x = 0; x < width; x++) {
                board[y][x] = Integer.parseInt(st.nextToken());
                if (board[y][x] == 2) { // virus
                    viruses.add(new int[]{y, x});
                } else if (board[y][x] == 0) {
                    safeCount++;
                }
            }
        }
        br.close();
        makeWalls(0);
        bw.write(result + "\n");
        bw.close();
    }

    public static void bfs() {
        int[][] temp_board = new int[height][width];
        for (int y = 0; y < height; y++) {
            temp_board[y] = Arrays.copyOf(board[y], board[y].length);
        }

        Queue<int[]> queue = new LinkedList<>(viruses);
        int count = 0;

        while (!queue.isEmpty()) {
            int[] cur = queue.poll();

            for (int i = 0; i < 4; i++) {
                int addY = cur[0] + dy[i];
                int addX = cur[1] + dx[i];

                if (isValidPosition(addY, addX) && temp_board[addY][addX] == 0) {
                    temp_board[addY][addX] = 2;
                    count++;
                    queue.add(new int[]{addY, addX});
                }
            }
        }

        int calc = safeCount - count - 3;
        result = Math.max(result, calc);
    }

    public static boolean isValidPosition(int y, int x) {
        return y >= 0 && y < height && x >= 0 && x < width;
    }

    public static void makeWalls(int count) {
        if (count == 3) {
            bfs();
            return;
        }

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (board[y][x] == 0) {
                    board[y][x] = 1;
                    makeWalls(count + 1);
                    board[y][x] = 0; // backtrack
                }
            }
        }

    }

}

 

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

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

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

[JAVA-자바] 17144번: 미세먼지 안녕!  (0) 2025.05.18
[JAVA-자바] 14938번: 서강그라운드  (0) 2025.05.16
[JAVA-자바] 12851번: 숨바꼭질 2  (0) 2025.05.14
[JAVA-자바] 11404번: 플로이드  (0) 2025.05.13
[JAVA-자바] 11054번: 가장 긴 바이토닉 부분 수열  (0) 2025.05.12
'알고리즘/백준' 카테고리의 다른 글
  • [JAVA-자바] 17144번: 미세먼지 안녕!
  • [JAVA-자바] 14938번: 서강그라운드
  • [JAVA-자바] 12851번: 숨바꼭질 2
  • [JAVA-자바] 11404번: 플로이드
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)
  • 블로그 메뉴

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

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
raven
[JAVA-자바] 14502번: 연구소
상단으로

티스토리툴바