알고리즘

[알고리즘] 백준 2636 - 치즈

blueberrysoda 2024. 7. 31. 23:09
#include <iostream>
#include <queue>
using namespace std;

int N, M;
int Arr[101][101];
bool Visit[101][101];
int Dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int Cheese;

void init(){
    for(int i=0; i<101; i++){
        for(int j=0; j<101; j++){
            Visit[i][j] = false;
        }
    }
    return;
}

void air(){
    init();
    queue<pair<int, int>> Q;
    Q.push({0, 0});
    Visit[0][0] = true;

    while(Q.empty() == false){
        int y = Q.front().first;
        int x = Q.front().second;
        Q.pop();

        for(int i=0; i<4; i++){
            int ny = y + Dir[i][0];
            int nx = x + Dir[i][1];
            
            if(ny < 0 || nx < 0 || ny >= N || nx >= M) continue;
            if(Visit[ny][nx] == true) continue;
            
            if(Arr[ny][nx] == 0){
                Q.push({ny, nx});
            }
            else{
                Arr[ny][nx] = 0;
                Cheese--;
            }
            Visit[ny][nx] = true;
        }
    }
    return;
}

int main(){
    cin >> N >> M;
    for(int i=0; i<N; i++){
        for(int j=0; j<M; j++){
            cin >> Arr[i][j];
            if(Arr[i][j] == 1){
                Cheese++;
            }
        }
    }

    int Ans = 0;
    int tmp = Cheese;
    while(Cheese > 0){
        air();
        if(Cheese != 0){
            tmp = Cheese;
        }
        Ans++;
    }

    cout << Ans << "\n" << tmp << "\n";

    return 0;
}