카테고리 없음

백준 7576번 : 토마토

show2888 2019. 9. 16. 22:55
반응형

https://www.acmicpc.net/problem/7576

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마

www.acmicpc.net

 

#include <iostream>
#include <queue>

using namespace std;

int x, y, tx, ty, nx, ny,cur_day;
int arr[1000][1000];
bool flag[1000][1000];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};

struct tomato
{
    int x, y, day;
};

queue<tomato> q;

int main()
{
    cin >> y >> x;

    for (int i = 0; i < x; i++)
    {
        for (int j = 0; j < y; j++)
        {
            cin >> arr[i][j];
        }
    }

    //find tomato
    for (int i = 0; i < x; i++)
    {
        for (int j = 0; j < y; j++)
        {
            if (arr[i][j] == 1)
            {
                flag[i][j] = true;
                tomato tmt={i, j, 0};
                q.push(tmt);
            }
            if(arr[i][j] == -1)
            {
                flag[i][j] = true;
            }
        }
    }
    //spread tomato
    while (!q.empty())
    {
        tx = q.front().x;
        ty = q.front().y;
        cur_day = q.front().day+1;
        q.pop();
        
        for (int i = 0; i < 4; i++)
        {
            nx = tx + dx[i];
            ny = ty + dy[i];

            if (!arr[nx][ny] && !flag[nx][ny] && nx >= 0 && ny >= 0 && nx < x && ny < y)
            {
                tomato tmt={nx,ny,cur_day};
                flag[nx][ny] = true;
                q.push(tmt);
            }
        }
    }
    
    // find zero
    for (int i = 0; i < x; i++)
    {
        for (int j = 0; j < y; j++)
        {
            if (flag[i][j] == 0)
            {
                cout << -1 << endl;
                return 0;
            }
        }
        
    }

    cout << cur_day-1;
}
반응형