출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 2573 빙산(dfs)

알고리즘

by 장동균 2020. 7. 27. 23:49

본문

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);
    }
}

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++;
                    dfs(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;    
    }
}

사실상 어려운 문제는 아니었지만, 체크해야하는 지점들이 여러개 있어서 꽤 시간이 걸렸다. 크게 코드에 대해 설명할 부분은 없는 것 같다.

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

백준 2146 다리 만들기(dfs, bfs)  (0) 2020.07.28
백준 2573 빙산(bfs)  (0) 2020.07.28
백준 2960 에라토스테네스의 체(구현)  (0) 2020.07.27
백준 2583 영역 구하기(bfs)  (0) 2020.07.27
백준 1707 이분 그래프(dfs)  (0) 2020.07.26

관련글 더보기

댓글 영역