백준 7576번 토마토

빵어 ㅣ 2023. 3. 16. 22:39

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int m, n;
int graph[1001][1001];
queue<pair<int, int>> q;

int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { -1, 1, 0, 0 };

int bfs() {
	int a = 0, b = 0;
	while (!q.empty()) {
		a = q.front().first;
		b = q.front().second;
		q.pop();

		for (int i = 0; i < 4; ++i) {
			int nx = a + dx[i];
			int ny = b + dy[i];

			if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
			if (graph[nx][ny] == 1 || graph[nx][ny] == -1) continue;

			if (graph[nx][ny] == 0) {
				graph[nx][ny] = graph[a][b] + 1;
				q.push({ nx, ny });
			}
		}
	}

	for (int i = 0; i < n; ++i)
		for (int j = 0; j < m; ++j)
			if (graph[i][j] == 0)
				return -1;

	return graph[a][b] - 1;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> m >> n;

	for (int i = 0; i < n; ++i)
		for (int j = 0; j < m; ++j) {
			cin >> graph[i][j];
			if (graph[i][j] == 1)
				q.push({ i, j });
		}
	
	cout << bfs();
	
	return 0;
}

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net

 

'알고리즘 공부' 카테고리의 다른 글

백준 1018번 체스판 다시 칠하기  (0) 2023.08.21
백준 1697번 숨바꼭질  (0) 2023.03.21
백준 2178번 미로 탐색  (0) 2023.03.16
백준 10026번 적록색약  (0) 2023.03.16
백준 11724번 연결 요소의 개수  (0) 2023.03.13