[BOJ] 7576 -토마토(G5)

suhyun·2022년 11월 30일
0

백준/프로그래머스

목록 보기
41/81

문제 링크

7576-토마토


입력

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다.
M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다.

둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다.
즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다.
하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다.
정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.

토마토가 하나 이상 있는 경우만 입력으로 주어진다.


출력

여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다.
만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.


문제 풀이

일반적인 bfs 문제였던거 같다
처음에 약간 헷갈린 부분은 익은 토마토가 하나가 아닌 경우

그 부분은 아래와 같이 처리

if (tomatos[nx][ny] == 0) {
	tomatos[nx][ny] = tomatos[x][y] + 1;
	queue.add(new int[]{nx, ny});
}

이 부분은 다시 생각해보고 넘어가는게 좋을 것 같다!

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

public class Main {
    static int[][] tomatos;
    static int N, M;
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    static Queue<int[]> queue = new LinkedList<>();

    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());

        tomatos = new int[N][M];

        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < M; j++) {
                tomatos[i][j] = Integer.parseInt(st.nextToken());
                if (tomatos[i][j] == 1) {
                    queue.add(new int[]{i, j});
                }
            }
        }
        System.out.println(bfs());
    }

    static int bfs() {
        while (!queue.isEmpty()) {
            int[] tmp = queue.poll();
            int x = tmp[0];
            int y = tmp[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) continue;
                if (tomatos[nx][ny] == 0) {
                
                	// 날짜를 얻기 위한 처리
                    tomatos[nx][ny] = tomatos[x][y] + 1;
                    queue.add(new int[]{nx, ny});
                }
            }
        }

        int max = Integer.MIN_VALUE;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
            	// 토마토가 안익은게 있으면 
                if(tomatos[i][j] == 0) return -1;
                
                // 날짜 최댓값
                max = Math.max(max, tomatos[i][j]);
            }
        }
        return max - 1;
    }
}
profile
꾸준히 하려고 노력하는 편 💻

0개의 댓글