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

int graph[302][302];
int deep[302][302];
bool visited[302][302];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int n, m;
void bfs(int i, int j) {
    queue<pair<int, int>> Q;
    Q.push({i, j});
    visited[i][j] = true;
    while(!Q.empty()) {
        auto cur = Q.front(); Q.pop();
        for(int i = 0; i < 4; i++) {
            int nx = cur.first + dx[i];
            int ny = cur.second + dy[i];

            if(nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
            if(visited[nx][ny]) continue;
            if(graph[nx][ny] == 0) continue;

            visited[nx][ny] = true;
            Q.push({nx, ny});
        }
    }
}

int main() {
    cout.sync_with_stdio(0);
    cin.tie(0);

    cin >> n >> m;
    long long ans = 0;

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            cin >> graph[i][j];
        }
    }

    while(true) {
        for(int i = 0; i < n; i++) {
            fill(visited[i], visited[i] + m, false);
            fill(deep[i], deep[i] + m, 0);
        }
        int count = 0; // 빙산의 개수
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                /* 아직방문 X, 빙산일 때 BFS 수행*/
                if(!visited[i][j] && graph[i][j] != 0) {
                    bfs(i, j);
                    count++;
                }
            }
        }
        /* 빙산이 두개 이상이면 답을 출력하고 종료 */
        if(count >= 2) {
            cout << ans;
            return 0;
        }
        ans++; // 년도 증가

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(graph[i][j] != 0) {
                    int sea = 0;
                    if(i-1 >= 0 && graph[i-1][j] == 0) sea++;
                    if(i+1 < n && graph[i+1][j] == 0) sea++;
                    if(j-1 >= 0 && graph[i][j-1] == 0) sea++;
                    if(j+1 < m && graph[i][j+1] == 0) sea++;
                    deep[i][j] = sea;
                }
            }
        }

        /* 바다에 둘러싸인 부분만큼 빼주어 빙산을 갱신하고 종료조건 검사 */
        /* 전부다 바다(=0) 이 되면 while문을 탈출하고 0을 출력한다. */
        bool isAllZero = true;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < n; j++) {
                if(graph[i][j] != 0) {
                    graph[i][j] = graph[i][j] - deep[i][j];
                    if(graph[i][j] < 0) graph[i][j] = 0;
                }
                if(graph[i][j] != 0) isAllZero = false;
            }
        }
        if(isAllZero) break;

    }
    cout << 0;
    return 0;
}






https://www.acmicpc.net/problem/2573


맞왜틀 ㅠㅠㅠㅠ

논리에서도 이상함을 못찾겠슴다... 질문글 봐도 저랑 똑같은 경우가 없어서...ㅠㅠ