https://www.acmicpc.net/problem/7576
#include <iostream>
#include <queue>
using namespace std;
int M, N;
int dy[4] = { 1, 0, -1, 0 };
int dx[4] = { 0, 1, 0, -1 };
int tomato[1001][1001] = { 0, };
queue<pair<int, int>> q;
int next_val = 0;
int bfs_val = 0;
void BFS(int x, int y)
{
for (int i = 0; i < 4; i++)
{
int ny = y + dy[i];
int nx = x + dx[i];
if (ny >= 0 && ny < N && nx >= 0 && nx < M && tomato[ny][nx] == 0)
{
tomato[ny][nx] = 1;
next_val++;
q.push({ nx, ny });
}
}
return;
}
int main(void)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tmp;
cin >> M >> N;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
cin >> tomato[i][j];
if (tomato[i][j] == 1)
{
q.push({ j, i });
}
}
}
bfs_val = q.size();
next_val = 0;
int ret = 0;
while (!q.empty())
{
pair<int, int> start = q.front();
q.pop();
BFS(start.first, start.second);
bfs_val--;
if (bfs_val == 0)
{
bfs_val = next_val;
next_val = 0;
ret++;
}
}
ret--;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (tomato[i][j] == 0)
ret = -1;
}
}
cout << ret << "\n";
return 0;
}