[백준] 7576번 토마토 Java

dustle·2023년 3월 22일
1

토마토

토마토가 익는 날짜를 계산하는 문제입니다.

동서남북으로만 익는 구조이므로

public static int[] X = {1, -1, 0, 0};//동서남북
public static int[] Y = {0, 0, -1, 1};

좌표를 미리 배열에 저장하여 반복문을 사용했습니다.

날짜를 계산할 때 바로 전에 방문한 배열의 값에 날짜를 하나씩 더해서 계산했습니다.
익으면 0이 자연수로 바뀌기 때문에 visited 배열은 생략했습니다.(방문처리 자동)
그러면 1부터 날짜가 세어지므로 마지막에는 -1을 해야합니다.

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

public class Main {
    public static int N;
    public static int M;
    public static int[] X = {1, -1, 0, 0};//동서남북
    public static int[] Y = {0, 0, -1, 1};
    public static int[][] map;
    public static Queue<Xy> queue = new LinkedList<>();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        st = new StringTokenizer(br.readLine());
        M = Integer.parseInt(st.nextToken());
        N = Integer.parseInt(st.nextToken());

        map = new int[N][M];

        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < M; j++) {
                int tmp = Integer.parseInt(st.nextToken());
                map[i][j] = tmp;
                if(tmp == 1) queue.offer(new Xy(i,j));//큐에 익은 토마토 추가
            }
        }

        bfs();

        System.out.println(result());;

    }

    //토마토 날짜 계산 메소드
    private static int result() {
        int max = Integer.MIN_VALUE;

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if(map[i][j] == 0)
                    return -1;
                max = Math.max(max, map[i][j]);

            }
        }
        return max - 1;
    }

    private static void bfs() {
        while (!queue.isEmpty()) {
            Xy tmp = queue.poll();
            int x,y;
            for (int i = 0; i < 4; i++) {
                x = X[i];
                y = Y[i];
                //동서남북에서 배열을 벗어나지 않게 하기 위한 조건문
                if ((tmp.x + x) >= 0 && (tmp.x + x) < N && (tmp.y + y) >= 0 && (tmp.y + y) < M) {
                    if (map[(tmp.x + x)][(tmp.y + y)] == 0) {
                        queue.offer(new Xy(tmp.x + x, tmp.y + y));
                        //날짜 추가
                        map[tmp.x + x][tmp.y + y] = map[tmp.x][tmp.y] + 1;
                    }
                }
            }
        }
    }

    private static class Xy {
        private int x;
        private int y;

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

0개의 댓글

Powered by GraphCDN, the GraphQL CDN