백준 7576번 문제 c++ 풀이
문제
철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자 모양 상자의 칸에 하나씩 넣어서 창고에 보관한다.
창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.
토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.
입력
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.
토마토가 하나 이상 있는 경우만 입력으로 주어진다.
출력
여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다. 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.
아이디어
- 각 시작 지점에서 토마토가 안익은 곳까지의 거리를 구하는 문제로 환원
- 숫자를 입력받고 2차원 배열에 입력받은 숫자가 1이면 0, 0이면 INTMAX, -1이면 -1을 저장한다.
- BFS를 돌린다. 이 때 큐를 2개를 두어 하나는 찾을 위치 큐, 하나는 현재 단계 큐를 두어 탐색한다.
- 이제 2차원 배열에는 최소 거리만 저장되었기에 그 배열에서 최댓값을 찾고 출력한다.
1차 시도
#include <iostream>
#include <numeric>
#include <queue>
#include <vector>
using namespace std;
int N, M;
int levels[1000][1000];
vector<pair<int, int>> startPoints;
int moveX[4]{1, -1, 0, 0};
int moveY[4]{0, 0, 1, -1};
void bfs(int startX, int startY)
{
queue<pair<int, int>> q;
queue<int> floor;
int currentFloor = 0;
q.emplace(startX, startY);
floor.push(0);
while (!q.empty())
{
const int x = q.front().first;
const int y = q.front().second;
currentFloor = floor.front();
q.pop();
floor.pop();
for (int i = 0; i < 4; ++i)
{
const int newX = x + moveX[i];
const int newY = y + moveY[i];
if (newX >= 0 && newX < M && newY >= 0 && newY < N && levels[newY][newX] > 0 &&
currentFloor + 1 < levels[newY][newX])
{
q.emplace(newX, newY);
floor.emplace(currentFloor + 1);
levels[newY][newX] = currentFloor + 1 < levels[newY][newX] ? currentFloor + 1 : levels[newY][newX];
}
}
}
}
int main()
{
cin >> M >> N;
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < M; ++j)
{
int x;
cin >> x;
if (x == 1)
{
startPoints.emplace_back(j, i);
levels[i][j] = 0;
}
else if (x == 0)
levels[i][j] = numeric_limits<int>::max();
else if (x == -1)
{
levels[i][j] = -1;
}
}
}
int result = 0;
for (const auto& [fst, snd] : startPoints)
{
bfs(fst, snd);
}
for (int i = 0; i < N; ++i)
for (int j = 0; j < M; ++j)
{
int tmp = levels[i][j];
result = tmp > result ? tmp : result;
if (tmp == numeric_limits<int>::max())
{
cout << -1;
return 0;
}
}
cout << result;
}
결과시간 초과
1차 시도 실패 원인 분석
bfs 함수 호출을 여러번하여 불필요한 탐색 횟수를 늘린 것 같았다.
2차 시도
#include <iostream>
#include <numeric>
#include <queue>
#include <vector>
using namespace std;
int N, M;
int levels[1000][1000];
vector<pair<int, int>> startPoints;
int moveX[4]{1, -1, 0, 0};
int moveY[4]{0, 0, 1, -1};
void bfs()
{
queue<pair<int, pair<int, int>>> q;
for (const auto& [startX, startY] : startPoints)
{
q.push({0, {startX, startY}});
}
while (!q.empty())
{
const int x = q.front().second.first;
const int y = q.front().second.second;
const int currentFloor = q.front().first;
q.pop();
for (int i = 0; i < 4; ++i)
{
const int newX = x + moveX[i];
const int newY = y + moveY[i];
if (newX >= 0 && newX < M && newY >= 0 && newY < N && levels[newY][newX] > 0 &&
currentFloor + 1 < levels[newY][newX])
{
q.push({currentFloor + 1, {newX, newY}});
levels[newY][newX] = currentFloor + 1;
}
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> M >> N;
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < M; ++j)
{
int x;
cin >> x;
if (x == 1)
{
startPoints.emplace_back(j, i);
levels[i][j] = 0;
}
else if (x == 0)
levels[i][j] = numeric_limits<int>::max();
else
{
levels[i][j] = -1;
}
}
}
int result = 0;
bfs();
for (int i = 0; i < N; ++i)
for (int j = 0; j < M; ++j)
{
int tmp = levels[i][j];
result = tmp > result ? tmp : result;
if (tmp == numeric_limits<int>::max())
{
cout << -1;
return 0;
}
}
cout << result;
}
결과맞았습니다!!
깃헙 링크 : link
