백준 7576 토마토

1568 단어 algorithm백준BFSBFS

백준 7576

#include<bits/stdc++.h>
using namespace std;
int arr[1001][1001];
int vis[1001][1001];
int m, n;
int dx[4] = { 0,0,1,-1 };
int dy[4] = { -1,1,0,0 };
int main() {
	ios::sync_with_stdio(0); cin.tie(0);

	cin >> m >> n;

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

	while (!q.empty()) {
		pair<int, int > nxt = q.front();
		q.pop();

		for (int i = 0; i < 4; i++) {

			int nx = nxt.first + dx[i];
			int ny = nxt.second + dy[i];

			if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;

			if (vis[nx][ny] || arr[nx][ny] != 0) continue;

			q.push({ nx,ny });

			vis[nx][ny] = vis[nxt.first][nxt.second] + 1;

		}
	}

	int mx = 0; int flag = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (!vis[i][j] && !arr[i][j] ) {
				flag = 1;
				break;
			}
			mx = max(mx, vis[i][j]);
		}
	}
	if (flag) cout << -1 << '\n';
	else cout << mx << '\n';
}

좋은 웹페이지 즐겨찾기