리셋 되지 말자

[백준 7576]토마토 본문

알고리즘

[백준 7576]토마토

kyeongjun-dev 2020. 3. 11. 13:55
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;

queue<pair<int, int >> Q;
int day = 0;
pair<int, int> D[4] = {
	{-1, 0}, {0, 1}, {1, 0}, {0, -1}
	//위, 오른쪽, 아래, 왼쪽
};
int **make_array(int **arr, int col, int row) {

	arr = new int*[row];

	for (int i = 0; i < row; i++) {
		arr[i] = new int[col]();
	}

	for (int i = 0; i < row; i++) {
		for (int j = 0; j < col; j++) {
			cin >> arr[i][j];
			if (arr[i][j] == 1) {
				Q.push(make_pair(i, j));
				//cout << Q.front().first << ' ' << Q.front().second;
			}
		}
	}

	return arr;

}

int **BFS(int **arr, int col, int row) {
	int x = Q.front().first;
	int y = Q.front().second;

	Q.pop();

	for (int i = 0; i < 4; i++) {
		if (x + D[i].first >= 0 && x + D[i].first <= row - 1 && y + D[i].second >= 0 && y + D[i].second <= col - 1) {
			if (arr[x + D[i].first][y + D[i].second] == 0 && arr[x + D[i].first][y + D[i].second] != -1) {
				arr[x + D[i].first][y + D[i].second] = arr[x][y] + 1;
				day = arr[x][y] + 1;
				Q.push(make_pair(x + D[i].first, y + D[i].second));
			}
		}
	}

	return arr;
}

int main() {



	int **arr = NULL;

	int row, col;
	cin >> col >> row;

	arr = make_array(arr, col, row);


	while (!Q.empty()) {
		BFS(arr, col, row);
	}

	for (int i = 0; i < row; i++) {
		for (int j = 0; j < col; j++) {
			//cout << arr[i][j] << ' ';
			if (arr[i][j] == 0)
				day = -1;
		}
		//cout << '\n';
	}
	if (day == -1)
		cout << day;
	else if (day == 0)
		cout << day;
	else
		cout << day - 1;

	return 0;
}

 

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

[백준] N과M(1)  (0) 2020.05.17
[백준]N와 M(1)  (0) 2020.04.25
재귀로 짠 수열(?)  (0) 2020.04.25
[백준 9466] 텀 프로젝트  (0) 2020.03.12
[백준 1697] 숨바꼭질  (0) 2020.03.11
Comments