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

using ll = long long;

int n, m;
vector<vector<int>> grid;
vector<vector<int>> vis;

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

queue<pair<int,int>> q;

// DFS to mark the first island
void dfs(int x, int y){
    vis[x][y] = 1;
    grid[x][y] = 2;          // mark first island

    q.push({x, y});          // every cell becomes a BFS source

    for(int k = 0; k < 4; k++){
        int nx = x + dx[k];
        int ny = y + dy[k];

        if(nx >= 0 && nx < n && ny >= 0 && ny < m &&
           !vis[nx][ny] && grid[nx][ny] == 1){
            dfs(nx, ny);
        }
    }
}

int main(){

    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n >> m;

    grid.assign(n, vector<int>(m));
    vis.assign(n, vector<int>(m, 0));

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

    // Find first island
    bool found = false;

    for(int i = 0; i < n && !found; i++){
        for(int j = 0; j < m && !found; j++){
            if(grid[i][j] == 1){
                dfs(i, j);
                found = true;
            }
        }
    }

    vector<vector<int>> dist(n, vector<int>(m, 0));

    // Multi-source BFS
    while(!q.empty()){

        auto [x, y] = q.front();
        q.pop();

        for(int k = 0; k < 4; k++){

            int nx = x + dx[k];
            int ny = y + dy[k];

            if(nx < 0 || nx >= n || ny < 0 || ny >= m)
                continue;

            // Reached second island
            if(grid[nx][ny] == 1){
                cout << dist[x][y] << '\n';
                return 0;
            }

            // Expand only through water
            if(grid[nx][ny] == 0){

                grid[nx][ny] = 2;      // mark visited
                dist[nx][ny] = dist[x][y] + 1;
                q.push({nx, ny});
            }
        }
    }

    return 0;
}