#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second

int n, m, year=0;
int area[303][303];
int vis[303][303];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

bool check(int i, int j) { 
    //범위 밖
    if(i<0 || i>=n || j<0 || j>=m) return 1;
    else return 0;
}
void melt(){
    int zero[303][303]={0};
    for(int i=0; i<n; i++) {
        for(int j=0; j<m;j++){
            if(area[i][j]==0) continue;
            for(int idx=0; idx<4; idx++){
                int nx=i+dx[idx];
                int ny=j+dy[idx];
                if(check(nx,ny)) continue;
                if(area[nx][ny]==0) zero[i][j]++;
            }
        }
    }
    for(int i=0; i<n; i++) {
        for(int j=0; j<m;j++){
            if(area[i][j]==0) continue;
            area[i][j]=max(area[i][j]-zero[i][j],0);
        }
    }
}

int cnt_land(){
    for(int i=0; i<n; i++) fill(vis[i],vis[i]+m,-1);
    int cnt=0;

    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            if(area[i][j]==0 || vis[i][j]!=-1) continue;
            queue<pair<int,int>> q;
            q.push({i,j});
            vis[i][j]=1;
            cnt++;
            while(!q.empty()) {
                auto cur=q.front(); q.pop();
                for(int idx=0; idx<4; idx++){
                    int nx=cur.X+dx[idx];
                    int ny=cur.Y+dy[idx];
                    if(check(nx,ny) || area[nx][ny]==0 || vis[nx][ny]!=-1) continue;

                    vis[nx][ny]=1;
                    q.push({nx,ny});
                }
            }
        }
    }
    return cnt;
}
int main() {
    cin>>n>>m;
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cin >> area[i][j];
        }
    }
    while(1){
        int island=cnt_land();
        if(island>=2) {
            cout << year;
            return 0;
        } 
        if(island==0) {
            cout << 0;
            return 0;
        }
        melt();
        year++;
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: