본문 바로가기
알고리즘/BFS

[백준 2638] 자바 / 치즈 / bfs

by 순원이 2024. 7. 23.

#문제         

레벨: G3
알고리즘: bfs 

풀이시간: 1시간
힌트 참조 유무: 유

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


#문제 풀이        

 

1. 2변이상 접촉 시 1시간만에 다 녹음 
2. 치즈 내부에 있는 경우에는 안 녹음
3. 치즈가 다 녹는데 걸리는 시간은? 

이 문제의 중심은 치즈의 안인지 밖인지 어떻게 판단할 것인지이다.

처음엔 치즈 안 쪽을 표시해야겠다고 생각했다. 그러나 구현이 복잡해 보였다.(알고리즘 문제에서 구현이 복잡하면 웬만하면 올바른 방향으로 풀이되는 게 아님) 그래서  치즈 바깥 쪽을 표시하기로 결정했다. 치즈 바깥면을 구하는 건 bfs로 해결할 수 있다. 녹이기 전,  치즈 밖에 있는 (0,0)에서부터 bfs를 시작한다. 1을 만나면 aircontact[i][j]에 +1해준다. 그리고 for문을 돌면서 aircontact[i][j]가 2이상이고 cheese[i][j]가 1인(치즈)를  0으로 만들어준다.(녹여준다.) 이 과정이 1초이다. 이과정을 치즈배열이 다 0일 때까지 반복한다. 

인터넷에 많은 풀이가 있지만, 이 풀이가 가장 직관적이어서 이해하기 쉬운 것 같다.


#풀이 코드      

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

public class Main {
    static int N, M;
    static int[][] cheese;
    static int[][] airContact;
    static boolean[][] visited;
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        cheese = new int[N][M];
        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < M; j++) {
                cheese[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        int time = 0;
        while (true) {
            airContact = new int[N][M];
            visited = new boolean[N][M];
            bfs(0, 0);

            boolean melted = false;
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    if (cheese[i][j] == 1 && airContact[i][j] >= 2) {
                        cheese[i][j] = 0;
                        melted = true;
                    }
                }
            }

            if (!melted) break;
            time++;
        }

        System.out.println(time);
    }

    static void bfs(int x, int y) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{x, y});
        visited[x][y] = true;

        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            x = cur[0];
            y = cur[1];

            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 || visited[nx][ny]) continue;

                if (cheese[nx][ny] == 0) {
                    visited[nx][ny] = true;
                    queue.offer(new int[]{nx, ny});
                } else if (cheese[nx][ny] == 1) {
                    airContact[nx][ny]++;
                }
            }
        }
    }
}

#비슷한 유형   

https://jsw5913.tistory.com/173

 

[백준 2573] 빙산 / 자바 / dfs

#문제         레벨:  G4알고리즘:  dfs풀이시간: 1시간힌트 참조 유무:https://www.acmicpc.net/problem/2573  #문제 풀이        이 문제는 두가지를 구현하면 되는 문제이다.1. 빙산의 개수 카운팅 함

jsw5913.tistory.com