출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]
https://www.acmicpc.net/problem/2573
2573번: 빙산
첫 줄에는 이차원 배열의 행의 개수와 열의 개수를 나타내는 두 정수 N과 M이 한 개의 빈칸을 사이에 두고 주어진다. N과 M은 3 이상 300 이하이다. 그 다음 N개의 줄에는 각 줄마다 배열의 각 행을 �
www.acmicpc.net
#include <iostream>
#include <queue>
using namespace std;
const int MAX = 300;
int graph[MAX][MAX];
bool visited[MAX][MAX];
int N, M;
int result;
int tmpGraph[MAX][MAX];
int block;
typedef struct
{
int x, y;
} Dir;
Dir dirMove[4] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
bool allZero()
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (graph[i][j] != 0)
return false;
}
}
return true;
}
void meltingIceberg(int x, int y)
{
int cnt = 0;
for (int i = 0; i < 4; i++)
{
int nextX = x + dirMove[i].x;
int nextY = y + dirMove[i].y;
if (0 <= nextX && nextX < N && 0 <= nextY && nextY < M && graph[nextX][nextY] == 0)
cnt++;
}
if (graph[x][y] - cnt >= 0)
tmpGraph[x][y] = graph[x][y] - cnt;
else
tmpGraph[x][y] = 0;
}
void dfs(int x, int y)
{
visited[x][y] = true;
for (int i = 0; i < 4; i++)
{
int nextX = x + dirMove[i].x;
int nextY = y + dirMove[i].y;
if (0 <= nextX && nextX < N && 0 <= nextY && nextY < M && !visited[nextX][nextY] && graph[nextX][nextY] != 0)
dfs(nextX, nextY);
}
}
void bfs(int x, int y)
{
queue<pair<int, int>> q;
q.push(make_pair(x, y));
visited[x][y] = true;
while (!q.empty())
{
int curX = q.front().first;
int curY = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int nextX = curX + dirMove[i].x;
int nextY = curY + dirMove[i].y;
if (0 <= nextX && nextX < N && 0 <= nextY && nextY < M && !visited[nextX][nextY] && graph[nextX][nextY] != 0)
{
visited[nextX][nextY] = true;
q.push(make_pair(nextX, nextY));
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> N >> M;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
cin >> graph[i][j];
}
}
while (1)
{
if (allZero())
{
cout << 0;
return 0;
}
result++;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
meltingIceberg(i, j);
}
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
graph[i][j] = tmpGraph[i][j];
}
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (!visited[i][j] && graph[i][j] != 0)
{
block++;
bfs(i, j);
}
}
}
if (block >= 2)
{
cout << result;
break;
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
visited[i][j] = false;
}
}
block = 0;
}
}
어제 똑같은 코드였는데 노트북이 맛이 갔엇는지 아무 것도 출력이 되지 않아 무한루프에 빠진 줄 알았더니 아니었다....
백준 9466 텀 프로젝트(dfs with cycle graph) (0) | 2020.08.01 |
---|---|
백준 2146 다리 만들기(dfs, bfs) (0) | 2020.07.28 |
백준 2573 빙산(dfs) (0) | 2020.07.27 |
백준 2960 에라토스테네스의 체(구현) (0) | 2020.07.27 |
백준 2583 영역 구하기(bfs) (0) | 2020.07.27 |
댓글 영역