본문 바로가기
Algorithm/Java

[Java]백준 7576번 :: 토마토

by dev_mac-_- 2019. 3. 12.

백준 온라인 저지 7576번 - 토마토

Java 알고리즘 문제풀이

풀이

BFS(너비 우선 탐색) 문제입니다.

BFS를 이용해 해결하는 문제는 3가지 조건을 가지고 있다.

1. 최소 비용 문제

2. 간선의 가중치가 1이다.

3. 정점과 간선의 개수가 적다. (시간제한, 메모리 제한 내에 만족한다.)

DFS, BFS 관련 자료 : https://developer-mac.tistory.com/64

 

토마토 문제에서는 BFS를 이용하면 된다.

익은 토마토를 큐에 담아 좌, 우, 위, 아래 총 4가지 경로를 탐색해주면된다.

이때 익은 토마토 기준으로 다른 칸으로 갈때 (안익은 토마토 0이 있을 때만, 비어 있는 공간 -1일 때는 제외한다.) 

이전 값에서 +1을 해주면서 전체를 탐색하면 된다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

class Pair2 {
    int x;
    int y;

    Pair2(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Beak7576 {
    static int[] dx = { 0, 0, -1, 1 };
    static int[] dy = { -1, 1, 0, 0 };

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

        String[] str1 = br.readLine().split(" ");

        int m = Integer.parseInt(str1[0]);
        int n = Integer.parseInt(str1[1]);

        int[][] arr = new int[n][m];
        int[][] dist = new int[n][m];

        Queue<Pair2> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            String[] str2 = br.readLine().split(" ");
            for (int j = 0; j < m; j++) {
                arr[i][j] = str2[j].charAt(0) - '0';
                if (arr[i][j] == 1) {
                    queue.add(new Pair2(i, j));
                }
            }
        }

        while (!queue.isEmpty()) {
            Pair2 p = queue.remove();
            int x = p.x;
            int y = p.y;
            for (int i = 0; i < dx.length; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];

                if (0 <= nx && nx < n && 0 <= ny && ny < m) {
                    if (arr[nx][ny] == 0 && dist[nx][ny] == 0) {
                        queue.add(new Pair2(nx, ny));
                        dist[nx][ny] = dist[x][y] + 1;
                    }
                }
            }
        }

        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                ans = Math.max(ans, dist[i][j]);
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (arr[i][j] == 0 && dist[i][j] == 0) {
                    ans = -1;
                }
            }
        }

        System.out.println(ans);
    }
}

댓글