https://www.acmicpc.net/problem/2573
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, m;
vector<vector<int>> iceberg;
int dx[] = { -1, 1, 0, 0 };
int dy[] = { 0, 0, -1, 1 };
void bfs(int x, int y, vector<vector<bool>>& visited)
{
queue<pair<int, int>> q;
q.push({ x, y });
visited[x][y] = true;
while (!q.empty()) {
int cx = q.front().first, cy = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = cx + dx[i], ny = cy + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && iceberg[nx][ny] > 0 && !visited[nx][ny])
{
visited[nx][ny] = true;
q.push({ nx, ny });
}
}
}
}
// 빙산 녹이기
void meltIceberg() {
vector<vector<int>> temp = iceberg;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (iceberg[i][j] > 0)
{
int seaCount = 0;
for (int k = 0; k < 4; k++)
{
int nx = i + dx[k], ny = j + dy[k];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && iceberg[nx][ny] == 0) seaCount++;
}
temp[i][j] = max(0, iceberg[i][j] - seaCount);
}
}
}
iceberg = temp;
}
// 빙산 덩어리 개수 세기
int countChunks()
{
vector<vector<bool>> visited(n, vector<bool>(m, false));
int chunks = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (iceberg[i][j] > 0 && !visited[i][j])
{
bfs(i, j, visited);
chunks++;
}
}
}
return chunks;
}
int main()
{
cin >> n >> m;
iceberg.resize(n, vector<int>(m));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> iceberg[i][j];
int time = 0;
while (true)
{
int chunks = countChunks();
if (chunks >= 2)
{ // 두 덩어리로 분리
cout << time << "\n";
break;
}
if (chunks == 0)
{ // 빙산이 모두 녹음
cout << 0 << "\n";
break;
}
meltIceberg();
time++;
}
return 0;
}
백준 / 2529 / 백트랙킹 (0) | 2025.02.05 |
---|---|
백준 1051 숫자 정사각형 (0) | 2025.02.04 |
백준 1707 // (0) | 2025.01.23 |
백준 2667 //단지번호붙이기 (0) | 2025.01.22 |
백준 1697//숨바꼭질 (0) | 2025.01.21 |