JW

 

 

#include <bits/stdc++.h>
using namespace std;
//토마토

int main() {
	queue<pair<int, int>> q;
	int n, m;
	int arr[1002][1002] = {0,}, visited[1002][1002] = {0,};
	cin >> n >> m;
	for (int i=1; i<=m; i++) {
		for (int j=1; j<=n; j++) {
			cin >> arr[i][j];
		}
	}

	for (int i=1; i<=m; i++) {
		for (int j=1; j<=n; j++) {
			if (arr[i][j] == 1) {
				q.push({i, j});
				visited[i][j] = 1;
			}
			else if (arr[i][j] == -1) {
				visited[i][j] = 1;
			}
		}
	}
	while (!q.empty()) {
		int x = q.front().first;
		int y = q.front().second;
		q.pop();
		if (x-1 != 0 && arr[x-1][y] == 0 && visited[x-1][y] == 0) {
			q.push({x-1, y});
			arr[x-1][y] = arr[x][y] + 1;
			visited[x-1][y] = 1;
		}
		if (x+1 != m+1 && arr[x+1][y] == 0 && visited[x+1][y] == 0) {
			q.push({x+1, y});
			arr[x+1][y] = arr[x][y] + 1;
			visited[x+1][y] = 1;
		}
		if (y-1 != 0 && arr[x][y-1] == 0 && visited[x][y-1] == 0) {
			q.push({x, y-1});
			arr[x][y-1] = arr[x][y] + 1;
			visited[x][y-1] = 1;
		}
		if (y+1 != n+1 && arr[x][y+1] == 0 && visited[x][y+1] == 0) {
			q.push({x, y+1});
			arr[x][y+1] = arr[x][y] + 1;
			visited[x][y+1] = 1;
		}
	}
	for (int i=1; i<=m; i++) {
		for (int j=1; j<=n; j++) {
			if (visited[i][j] == 0) {
				printf("-1");
				return 0;
			}
		}
	}
	int maxi = 0;
	for (int i=1; i<=m; i++) {
		for (int j=1; j<=n; j++) {
			if (arr[i][j] > maxi) {
				maxi = arr[i][j];
			}
		}
	}
	printf("%d", maxi-1);
}

 

 

'정보올림피아드-KOI > BOJ' 카테고리의 다른 글

백준 균형잡힌 세상  (0) 2022.03.07
백준 소수 구하기 1929  (0) 2022.03.07
스택 Stack  (0) 2022.02.04
단어 뒤집기 2  (0) 2021.12.31
백준 : 가운데를 말해요 1655번  (0) 2020.05.10

+ Recent posts