티스토리 뷰

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

 

코드

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

public class Main {

    static int n, m;
    static int[][] arr;
    static boolean[][] visited;
    static Queue<Point> que;

    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());
        m = Integer.parseInt(st.nextToken());
        n = Integer.parseInt(st.nextToken());

        arr = new int[n][m];
        visited = new boolean[n][m];
        que = new LinkedList<>();

        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < m; j++) {
                int num = Integer.parseInt(st.nextToken());
                arr[i][j] = num;
                if (num == 1) {
                    que.add(new Point(j, i));
                }
            }
        }

        int days = bfs();
        if (isNotRipeAllTomato()) {
            System.out.println(-1);
        } else {
            System.out.println(days);
        }
    }

    static int bfs() {
        int days = 0;

        Queue<Point> waitQue = new LinkedList<>();
        while (!que.isEmpty()) {
            Point p = que.poll();
            for (int d = 0; d < 4; d++) {
                int cx = p.x + dx[d];
                int cy = p.y + dy[d];
                if (isNotOutOfRange(cx, cy)) {
                    if (arr[cy][cx] == 0) {
                        arr[cy][cx] = 1;
                        waitQue.offer(new Point(cx, cy));
                    }
                }
            }

            if (que.isEmpty()) {
                days++;
                while (!waitQue.isEmpty()) {
                    que.offer(waitQue.poll());
                }
            }

        }

        return days - 1;
    }

    static boolean isNotRipeAllTomato() {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (arr[i][j] == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    static boolean isNotOutOfRange(int x, int y) {
        if (x >= 0 && x < m && y >= 0 && y < n) {
            return true;
        }
        return false;
    }

    static class Point {

        int x, y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}
Total
Today
Yesterday
최근에 올라온 글
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30