#include <iostream>
#include <string>
#include <queue>
#include <algorithm>

using namespace std;
#define X first
#define Y second
int board[1002][1002];
int day[1002][1002];

int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n,m;
    queue<pair<int,int>> q;
    cin >> m >> n;
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cin >> board[i][j];
        }
    }
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            if(board[i][j]==1) {
                q.push({i,j});
                day[i][j]=0;
            }
        }
    }
    while(!q.empty()) {
        pair<int,int> cur=q.front();
        q.pop();
        for(int i=0; i<4; i++) {
            int nx=cur.X+dx[i];
            int ny=cur.Y+dy[i];

            if(nx<0 || nx>=n || ny <0 || ny >=m) continue;
            //!익지않은 토마토 
            if(board[nx][ny]!=0  ) continue;
            //익지않은 토마토 탐색
            board[nx][ny]=1;
            day[nx][ny]=day[cur.X][cur.Y]+1;
            q.push({nx,ny});
        }
    }
    int res=0;
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            if(board[i][j]==0) {
                cout << -1;
                return 0;
            }
            res=max(res,day[i][j]);
        }
    }
    cout << res;
}

Embed on website

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