BOJ 7576번 토마토

|


import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;

public class BOJ_7576 {

    static int[][] adj;
    static int n;
    static int m;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] s = sc.nextLine().split("\\s");
        m = Integer.parseInt(s[0]);
        n = Integer.parseInt(s[1]);

        adj = new int[n][m];
        for (int i = 0; i < n; i++) {
            adj[i] = Arrays.stream(sc.nextLine().split("\\s")).mapToInt(Integer::parseInt).toArray();
        }
        solve();
    }

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

    private static void solve() {
        Queue<Tomato> tomatoes = new ArrayDeque<>();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (adj[i][j] == 1)
                    tomatoes.add(new Tomato(i, j));
            }
        }

        while (!tomatoes.isEmpty()) {
            Tomato tomato = tomatoes.poll();

            for (int i = 0; i < 4; i++) {
                int nextX = tomato.x + dx[i];
                int nextY = tomato.y + dy[i];

                if (nextX < 0 || nextY < 0 || nextX >= n || nextY >= m) {
                    continue;
                }

                if (adj[nextX][nextY] != 0) {
                    continue;
                }

                adj[nextX][nextY] = adj[tomato.x][tomato.y] + 1;
                tomatoes.add(new Tomato(nextX, nextY));
            }
        }

        int max = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(adj[i][j] == 0){
                    System.out.println(-1);
                    return;
                }
                max = Math.max(max,adj[i][j]);
            }
        }
        System.out.println(max-1);
    }

    static class Tomato {
        int x;
        int y;

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

}