토마토


#include <iostream>
#include <queue>
#include <stdio.h>
#include <string>
#include <cmath>
#include <algorithm>

int arr[1001][1001];
int visited[1001][1001];
bool Done[50][50];
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };




int main() {
	int m, n, i, j;
	int seg = 0, cnt = 0, ans = 0;
	scanf("%d %d", &m, &n);
	std::queue<std::pair<int, int>> q;
	bool f = true;
	for (i = 0;i < n;i++) {
		for (int j = 0;j < m;j++) {
			scanf("%d", &arr[i][j]);
			if (arr[i][j] == 1) {
				q.push(std::make_pair(i, j));
				seg++;
			}
			else if (arr[i][j] == 0) {
				f = false;
			}
		}
	}
	if (f) {
		printf("0\n");
		return 0;
	}
	bool flag = false;
	while (!q.empty()) {
		cnt = 0;
		for (i = 0;i < seg;i++) {
			std::pair<int, int> newc = q.front();
			q.pop();

			visited[newc.first][newc.second] = 1;

			for (j = 0;j < 4;j++) {
				int nx = newc.second + dx[j];
				int ny = newc.first + dy[j];

				if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
					if (arr[ny][nx] == 0 && visited[ny][nx] == 0) {
						arr[ny][nx] = arr[newc.first][newc.second]+1;
						q.push(std::make_pair(ny, nx));
						cnt++;
					}
				}
			}
		}
		seg = cnt;
		if (flag) ans++;
	}
	for (i = 0;i < n;i++) {
		for (j = 0;j < m;j++) {
			if (arr[i][j] == 0) {
				printf("-1\n");
				return 0;
			}
		}
	}
	int result = 0;
	for (i = 0;i < n;i++) {
		for (j = 0;j < m;j++) {
			if (result < arr[i][j]) {
				result = arr[i][j];
			}
		}
	}
	printf("%d\n", result - 1);
	return 0;
}

좋은 웹페이지 즐겨찾기