본문 바로가기

정리해두는거/알고리즘

토마토

728x90
반응형
SMALL

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net

 

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

int row, col;
int tomatoCnt;
int days;
vector<pair<int,int>> tomatoPos;
vector<vector<int>> tomatoMap;

int dr[4] = {0,0,1,-1};
int dc[4] = {1,-1,0,0};

void input()
{
    cin >> col >> row;
    tomatoCnt=0;
    days = 0;
    tomatoMap.resize(row, vector<int>(col,0));

    for(int i=0; i <row; i++)
    {
        for(int j=0; j < col; j++)
        {
            cin >> tomatoMap[i][j];
            if(tomatoMap[i][j] == 1)
            {
                tomatoPos.push_back(make_pair(i,j));
            }

            if(tomatoMap[i][j] == 0)tomatoCnt++;
        }
    }
}

void bfs()
{
    queue<pair<int,int>> q;

    for(auto a : tomatoPos)
    {
        q.push(a);
    }

    while(!q.empty())
    {
        size_t qSize = q.size();
        bool isRipe = false;

        for(int i=0; i < qSize; i++)
        {
            int r = q.front().first;
            int c = q.front().second;
            q.pop();

            for(int d=0; d < 4; d++)
            {
                int nR = r + dr[d];
                int nC = c + dc[d];

                if(nR < 0 || nR >= row || nC < 0 || nC >=col)continue;

                if(tomatoMap[nR][nC] == 1 || tomatoMap[nR][nC] == -1) continue;

                tomatoMap[nR][nC] = 1;
                tomatoCnt--;
                isRipe = true;
                q.push(make_pair(nR, nC));
            }
        }

        if(isRipe)days++;
    }
}

int main()
{
    input();

    bfs();

    if(tomatoCnt == 0)cout << days;
    else cout << "-1";
}
728x90
반응형
LIST

'정리해두는거 > 알고리즘' 카테고리의 다른 글

미로 탐색  (0) 2024.02.18
설탕 배달 (dp)  (1) 2024.02.17
설탕 배달 (그냥 구현)  (0) 2024.02.17
마법사 상어와 파이어볼  (0) 2024.02.16
XCode에서 연습하게 되었다  (0) 2024.02.04