본문 바로가기
Algorithms/BOJ

[BOJ] 7576 토마토(Java)

by 그냥팬더 2021. 5. 1.
반응형

토마토


전체 방향에서 상하좌우. 4방향의 영향을 받으므로 기존의 익은 토마토를 LinkedList에 삽입 후 처리를 진행했다.

그리고 기존의 좌표 뿐 아니라 날짜를 추가로 입력해 계속해서 계산을 실시했다.

마지막으로 전체 Box에서 안익은 토마토가 있으면 -1로 리턴해 마무리.

<전체 소스>

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

public class problem7576 {

    private static int N,M;
    private static int[][] box;
    private static int[] dr = {0, 0, -1, 1};
    private static int[] dc = {-1, 1, 0, 0};
    private static Queue<Position> tomatos;
    public static void main( String[] args ) throws IOException, NumberFormatException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");
        M = Integer.parseInt(st.nextToken());
        N = Integer.parseInt(st.nextToken());
        box = new int[N][M];

        tomatos = new LinkedList<>();
        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());
                box[i][j] = tmp;
                if(tmp == 1)
                    tomatos.offer(new Position(i, j, 0));
            }
        }

        solve();
    }

    static void solve(){
        int day = 0;
        while(!tomatos.isEmpty()){
            Position now = tomatos.poll();
            day = now.day;
            for(int i = 0; i<4; i++){
                int nr = dr[i] + now.r;
                int nc = dc[i] + now.c;
                if( nr >=0&& nr < N && nc>=0 && nc<M){
                    if(box[nr][nc]==0){
                        box[nr][nc] = 1;
                        tomatos.offer(new Position(nr,nc, now.day+1));
                    }
                }
            }
        }

        if(check())
            System.out.println(day);
        else
            System.out.println(-1);
    }

    static boolean check(){

        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                if (box[i][j] == 0)
                    return false;
            }
        }

        return true;
    }
}

class Position{
    int r;
    int c;
    int day;
    public Position(int r, int c, int day){
        this.r = r;
        this.c = c;
        this.day = day;
    }
}

[Github]

반응형

'Algorithms > BOJ' 카테고리의 다른 글

[BOJ] 17822 원판 돌리기(Java)  (0) 2021.05.01
[BOJ] 17143 낚시왕(Java)  (0) 2021.05.01

댓글