하다보니

7576번-토마토 본문

알고리즘 풀이/백준

7576번-토마토

claire 2022. 1. 29. 01:05
#include<bits/stdc++.h>
#define X first
#define Y second
using namespace std;

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

int main() {
	int n, m;
	queue<pair<int, int>> Q;
	cin >> m >> n;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> board[i][j];
			if (board[i][j] == 1)Q.push({ i,j });
			if (board[i][j] == 0)visited[i][j] = -1;
		}
	}
	while (!Q.empty()) {
		auto cur = Q.front(); Q.pop();
		for (int i = 0; i < 4; i++) {
			int nx = cur.X + dx[i];
			int ny = cur.Y + dy[i];
			if (nx < 0 || nx >= n || ny < 0 || ny >= m)continue;
			if ( visited[nx][ny] >= 0)continue;
			visited[nx][ny] = visited[cur.X][cur.Y] + 1;
			Q.push({ nx,ny });
		}
	}
	int ans = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (visited[i][j] == -1) {
				cout << -1;
				return 0;
			}
			ans = max(ans, visited[i][j]);
		}
	}
	cout << ans;
}

'알고리즘 풀이 > 백준' 카테고리의 다른 글

1697번-숨바꼭질  (0) 2022.02.03
1697번-불!  (0) 2022.01.30
2178번-미로탐색  (0) 2022.01.29
1926번-그림  (0) 2022.01.26
1021번-회전하는 큐  (0) 2022.01.23