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

6 4
1 -1 0 0 0 0
0 -1 0 0 0 0
0 0 0 0 -1 0
0 0 0 0 -1 1
출력 : 6
#include <iostream>
#include <queue>
#define MAX 1001
using namespace std;
int graph[MAX][MAX];
int cnt=0;
int n, m;
queue<pair<int, int>> q;
void bfs() {
	while (!q.empty()) {
		int x,y;
		x = q.front().first;
		y = q.front().second;
		q.pop();
		if (x > 0) {
			if (graph[x - 1][y] ==0) {
				q.push(make_pair(x - 1, y));
				graph[x - 1][y] = graph[x][y] + 1; //영향을 준 토마토의 값 +1
			}
		}
		if (x < m - 1) {
			if (graph[x+1][y] == 0) {
				q.push(make_pair(x + 1, y));
				graph[x + 1][y] = graph[x][y] + 1;
			}
		}
		if (y > 0) {
			if (graph[x][y - 1] == 0) {
				q.push(make_pair(x, y - 1));
				graph[x][y - 1] = graph[x][y] + 1;
			}
		}
		if (y < n - 1) {
			if (graph[x][y+1] == 0) {
				q.push(make_pair(x, y + 1));
				graph[x][y + 1] = graph[x][y] + 1;
			}
		}
	}
}
int main() {
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			cin >> graph[i][j];
			if (graph[i][j] == 1) q.push(make_pair(i, j)); //입력받으면서 바로 넣어줌
		}
	}
	bfs();
	int max = 0;
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (graph[i][j]==0) { //익지 않은 토마토가 있다면
				cout << "-1\n";
				return 0;
			}
			if (max < graph[i][j])
				max = graph[i][j]; //최댓값 저장
		}
	}
	cout << max-1 << "\n"; //맨처음 익은 토마토 값이 1이었으므로 빼줌
	return 0;
}