본문 바로가기

알고리즘

[백준] 연구소

문제

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

 

 

 

 

정답

나는 완전 탐색을 이용해서 벽을 세울 수 있는 경우의 수를 구했는데 DFS/BFS를 통해서도 구할 수 있는 모양이다.

풀이 방식은 다음과 같다.

  1. 벽 3개를 세울 수 있는 경우의 수 다 세워보기
  2. 벽이 세워진 후 바이러스 퍼지게 하기
  3. 바이러스 퍼진 후 안전 영역 개수 세기
  4. 안전 영역이 최댓값일 때를 저장해서 출력하기

 

[내 풀이]

import java.util.*;

public class Main {

    private static int[][] lab;
    private static int N, M;

    public static int BFS() {
        Queue<int[]> queue = new LinkedList<>();
        int[][] tmpLab = new int[N][M];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                tmpLab[i][j] = lab[i][j];
                if (lab[i][j] == 2) {
                    queue.add(new int[]{i, j});
                }
            }
        }
        int[] dx = {1, -1, 0, 0};
        int[] dy = {0, 0, 1, -1};
        while (!queue.isEmpty()) {
            int[] now = queue.poll();
            for (int i = 0; i < 4; i++) {
                int nx = now[0] + dx[i];
                int ny = now[1] + dy[i];
                if(nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
                if(tmpLab[nx][ny] == 0) {
                    tmpLab[nx][ny] = 2;
                    queue.add(new int[]{nx, ny});
                }
            }
        }
        return countSafeArea(tmpLab);
    }

    public static int countSafeArea(int[][] arr) {
        int safeArea = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if(arr[i][j] == 0) safeArea++;
            }
        }
        return safeArea;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        lab = new int[N][M];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                lab[i][j] = sc.nextInt();
            }
        }

        List<int[]> position = new ArrayList<>();
        // 2차원 좌표를 1차원 리스트로 변환
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                position.add(new int[]{i, j});
            }
        }
        int total = position.size();
        int answer = 0;
        for (int a = 0; a < total; a++) {
            for (int b = a + 1; b < total; b++) {
                for (int c = b + 1; c < total; c++) {
                    int[] p1 = position.get(a);
                    int[] p2 = position.get(b);
                    int[] p3 = position.get(c);
                    if(lab[p1[0]][p1[1]] != 0 || lab[p2[0]][p2[1]] != 0 || lab[p3[0]][p3[1]] != 0) continue;
                    lab[p1[0]][p1[1]] = 1;
                    lab[p2[0]][p2[1]] = 1;
                    lab[p3[0]][p3[1]] = 1;
                    int bfs = BFS();
                    answer = Math.max(answer, bfs);
                    lab[p1[0]][p1[1]] = 0;
                    lab[p2[0]][p2[1]] = 0;
                    lab[p3[0]][p3[1]] = 0;
                }
            }
        }
        System.out.println(answer);
    }
}

 

 

 

[다른 풀이]

import java.util.*;

public class Main {

    public static int n, m, result = 0;
    public static int[][] arr = new int[8][8]; // 초기 맵 배열
    public static int[][] temp = new int[8][8]; // 벽을 설치한 뒤의 맵 배열
    
    // 4가지 이동 방향에 대한 배열
    public static int[] dx = {-1, 0, 1, 0};
    public static int[] dy = {0, 1, 0, -1};

    // 깊이 우선 탐색(DFS)을 이용해 각 바이러스가 사방으로 퍼지도록 하기
    public static void virus(int x, int y) {
        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 < m) {
                if (temp[nx][ny] == 0) {
                    // 해당 위치에 바이러스 배치하고, 다시 재귀적으로 수행
                    temp[nx][ny] = 2;
                    virus(nx, ny);
                }
            }
        }
    }

    // 현재 맵에서 안전 영역의 크기 계산하는 메서드
    public static int getScore() {
        int score = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (temp[i][j] == 0) {
                    score += 1;
                }
            }
        }
        return score;
    }

    // 깊이 우선 탐색(DFS)을 이용해 울타리를 설치하면서, 매 번 안전 영역의 크기 계산
    public static void dfs(int count) {
        // 울타리가 3개 설치된 경우
        if (count == 3) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    temp[i][j] = arr[i][j];
                }
            }
            // 각 바이러스의 위치에서 전파 진행
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (temp[i][j] == 2) {
                        virus(i, j);
                    }
                }
            }
            // 안전 영역의 최대값 계산
            result = Math.max(result, getScore());
            return;
        }
        // 빈 공간에 울타리를 설치
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (arr[i][j] == 0) {
                    arr[i][j] = 1;
                    count += 1;
                    dfs(count);
                    arr[i][j] = 0;
                    count -= 1;
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        m = sc.nextInt();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = sc.nextInt();
            }
        }

        dfs(0);
        System.out.println(result);
    }
}

'알고리즘' 카테고리의 다른 글

[프로그래머스] 괄호 변환  (1) 2025.02.25
[백준] 경쟁적 전염  (0) 2025.02.24
[백준] 특정 거리의 도시 찾기  (0) 2025.02.24
[프로그래머스] 외벽 점검  (0) 2025.02.22
[LeetCode] Valid Parentheses  (0) 2024.03.29