https://www.acmicpc.net/problem/7576
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
const int MAX = 1000;
vector<vector<int>> box(MAX, vector<int>(MAX, 0));
bool visit[MAX][MAX] = {false, };
int n, m;
int di[] = {1, -1, 0, 0};
int dj[] = {0, 0, 1, -1};
queue<pair<pair<int, int>, int>> q;
int cnt;
// 토마토
void solution(){
while(!q.empty()){
int row = q.front().first.first;
int col = q.front().first.second;
cnt = q.front().second;
q.pop();
for(int i=0;i<4;i++){
int R = row + di[i];
int C = col + dj[i];
if(R>=n || R<0 || C>=m || C<0)
continue;
if(visit[R][C] == false && box[R][C] == 0){
visit[R][C] = true;
q.push(make_pair(make_pair(R, C), cnt +1));
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>m >>n;
vector<vector<int>> pair;
for(int j=0;j<n;j++){
for(int i = 0;i<m;i++){
cin>>box[j][i];
if(box[j][i] == 1){
q.push(make_pair(make_pair(j, i), 0));
visit[j][i] = true;
}
}
}
solution();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!visit[i][j] && box[i][j] == 0){
cout<<-1<<endl;
return 0;
}
}
}
cout<<cnt<<endl;
return 0;
}