코딩테스트/백준

[골5] 7576 - 토마토

ShovelingLife 2022. 7. 4. 20:55
#include <iostream>
#include <algorithm>
#include <exception>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <utility>

using namespace std;
using int_pair = pair<int, int>;

#define SIZE 1000
#define y first
#define x second

// 상 하 좌 우
int_pair arr_pos[]
{
    { 1, 0},
    {-1, 0},
    {0, -1},
    {0, 1}
};

vector<vector<int>> graph;

// w:넓이, h:높이, k:테스트 개수
int w, h, k;
queue<int_pair> q;

void BFS()
{
    while (!q.empty())
    {
        auto front = q.front(); q.pop();

        for (int i = 0; i < 4; i++)
        {
            int ny = front.y + arr_pos[i].y;
            int nx = front.x + arr_pos[i].x;

            if (nx < 0 ||
                nx >= w ||
                ny < 0 ||
                ny >= h)
                continue;

            if (graph[ny][nx] == 0)
            {
                q.push({ ny,nx });
                graph[ny][nx] = graph[front.y][front.x] + 1;
            }
        }
    }
}

int main()
{
    cin >> w >> h;

    // 그래프 입력
    graph.resize(h);

    for (int y = 0; y < h; y++)
    {
        graph[y].resize(w);

        for (int x = 0; x < graph[y].size(); x++)
        {
            cin >> graph[y][x];

            if (graph[y][x] == 1)
                q.push({ y,x });
        }
    }
    BFS();
    int result = 0;

    for (int y = 0; y < h; y++)
    {
        for (int x = 0; x < w; x++)
        {
            // 익지않은 토마토가 존재할 경우
            if (graph[y][x] == 0)
            {
                cout << -1;
                return 0;
            }
            // 익은 토마토일 시
            if (result < graph[y][x])
                result = graph[y][x];
        }
    }
    cout << result - 1;
    return 0;
}