[7576] 토마토

1 minute read

풀이

bfs를 시작할 때 q에 처음 토마토의 위치를 모두 넣고 시작합니다.

코드


#include <cstdio>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
#define MAX 1000
int map[MAX+1][MAX + 1];
bool check[MAX + 1][MAX + 1];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int n = 0, m = 0;
queue<pair<int, int> > q;

int bfs(queue<pair<int, int> >& q) {
	pair<int, int> curr, next;
	while (!q.empty()) {
		curr = q.front(); q.pop();
		for (int k = 0; k < 4; k++) {
			next.first = curr.first + dx[k];
			next.second = curr.second + dy[k];
			if (next.first < 0 || next.first >= n) continue;
			if (next.second < 0 || next.second >= m) continue;
			if (map[next.first][next.second] == 0 && check[next.first][next.second] == false) {
				map[next.first][next.second] = map[curr.first][curr.second] + 1;
				check[next.first][next.second] = true;
				q.push(make_pair(next.first, next.second));
			}
		}
	}
	return map[curr.first][curr.second] - 1;
}
int main(void) {
	scanf("%d%d", &m, &n);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf("%d", &map[i][j]);
		}
	}

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (map[i][j] == 1 && check[i][j] == false) {
				q.push(make_pair(i, j));
			}
		}
	}
	int ans = bfs(q);

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (map[i][j] == 0) {
				printf("-1\n");
				return 0;
			}
		}
	}
	printf("%d\n", ans);
	return 0;
}

Tags:

Categories:

Updated: