한줄 후기 : 토마토 먹고싶다.
https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마
www.acmicpc.net
#include <iostream>
#include <queue>
#include <utility>
using namespace std;
queue<pair<int, int>> tomatos;
int box[1001][1001];
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,1,0,-1 };
int n, m;
int total = 0;
int bfs();
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> box[i][j];
if (box[i][j] == 1)
tomatos.push(make_pair(i, j)); //큐 안에 이미 익어있는 애들 삽입
else if (box[i][j] == -1) total++; //나중에 총합 세려고 빈 토마토 개수 셈
}
}
cout << bfs();
return 0;
}
int bfs() {
pair<int, int> now;
int size, days = 0, nextx, nexty;
while (!tomatos.empty()) {
size = tomatos.size();
total += size;
if (total == n * m) return days; //total이 모든 토마토 수가 되었을 때 (비어있는 칸 포함)
for (int i = 0; i < size; i++) {
now = tomatos.front();
tomatos.pop();
for (int j = 0; j < 4; j++) {
nextx = now.first + dx[j];
nexty = now.second + dy[j];
if (nextx < m && nexty < n) {
if (nextx >= 0 && nexty >= 0) {
if (box[nextx][nexty] == 0) {
box[nextx][nexty] = 1;
tomatos.push(make_pair(nextx, nexty));
}
}
}
}
}
days++;
}
if (total != n * m) return -1;
}
'DEV > PS' 카테고리의 다른 글
[5567] 결혼식, C++ (0) | 2019.07.24 |
---|---|
[10451] 순열 싸이클, C++ (0) | 2019.07.24 |
[2606] 바이러스, C++ (0) | 2019.07.24 |
[11724] 연결 요소의 개수, C/C++ (0) | 2019.07.24 |
[11057] 오르막 수 , C++ (0) | 2019.07.23 |