마이 플밍 블로그

백준 7569 토마토 본문

카테고리 없음

백준 7569 토마토

레옹 2021. 7. 29. 15:41
#include<cstdio>
#include<iostream>
#include<queue>
#include <string>
using namespace std;

int M, N;
int box[1001][1001];

int Dx[4] = { -1,0,1,0 };
int Dy[4] = { 0,-1,0,1 };
int Day = 0;
int NotRipeTomatoNum = 0;
bool isInside(int x, int y) {
    if (0 <= x && x < M && 0 <= y && y < N) {
        return true;
    }
    return false;
}

bool RipeTomatoes(vector<int> &RipeTomatoX, vector<int> &RipeTomatoY) {
    int RipeTomatoIndex = 0;
    vector<int> RipeTomatoXpos;
    vector<int> RipeTomatoYpos;
    for(int i = 0; i < RipeTomatoX.size();i++)
    {
        int xPos = RipeTomatoX[i];
        int yPos = RipeTomatoY[i];

        for (int i = 0; i < 4; i++) {
            int boxX = xPos + Dx[i];
            int boxY = yPos + Dy[i];

            if (isInside(boxX, boxY)) {
                if (box[boxX][boxY] == 0) {
                    box[boxX][boxY] = 1;                   
                    RipeTomatoIndex++;
                    NotRipeTomatoNum--;

                    RipeTomatoXpos.push_back(boxX);        
                    RipeTomatoYpos.push_back(boxY);
                }
            }
        }
    }
    if (NotRipeTomatoNum == 0) {
        if(RipeTomatoIndex > 0)
            Day++;
        return true;
    }
    else if (RipeTomatoIndex > 0) {
        Day++;
        return RipeTomatoes(RipeTomatoXpos, RipeTomatoYpos);
    }
    return false;
}
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> M >> N;

    vector<int> RipeTomatoX;
    vector<int> RipeTomatoY;
    for (int y = 0; y < N; y++) {
        for (int x = 0; x < M; x++) {
            cin >> box[x][y];
            if (box[x][y] == 0)
                NotRipeTomatoNum++;
            else if (box[x][y] == 1) {
                RipeTomatoX.push_back(x);
                RipeTomatoY.push_back(y);
            }
        }
    }
    if (RipeTomatoes(RipeTomatoX, RipeTomatoY)) {
        cout << Day;
    }
    else {
        cout << "-1";
    }
    return 0;
}