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

vector<vector<int>> dir = {{0,1},{1,0},{-1,0},{0,-1}};

void performbfs (vector<vector<int>> & arr ,vector<vector<int>> & owner,int i,int j,int x)
{
	
	queue<pair<int,int>> q;
	q.push({i,j});
	owner[i][j]=x;
	while(q.size()!=0)
	{
		auto it = q.front();
		q.pop();
		int currI = it.first;
		int currJ = it.second;
		for(int k=0;k<4;k++)
		{
			int newI = currI + dir[k][0];
			int newJ = currJ + dir[k][1];
		if(newI>=0 && newI<arr.size() && newJ >=0 && newJ <arr[0].size() && arr[newI][newJ]==1 && owner[newI][newJ]==0)
		{
			owner[newI][newJ]=x;
			q.push({newI,newJ});
		}
		
		}
	}
}

int findminDist (	vector<vector<int>> &arr)
{
	int rows = arr.size();
	int cols = arr[0].size();
	vector<vector<int>> owner (rows,vector<int>(cols,0));
	vector<vector<int>> distance (rows,vector<int>(cols,-1));
	int x= 1;
	for(int i=0;i<rows;i++)
	{
		for(int j=0;j<cols;j++)
		{
			if(arr[i][j]==1 && owner[i][j]==0)
			{
				performbfs(arr,owner,i,j,x);
				x++;
			}
		}
	}
	queue<pair<int,int>> q;
	for(int i=0;i<rows;i++)
	{
		for(int j=0;j<cols;j++)
		{
			if(arr[i][j]==1)
			{
					q.push({i,j});
					distance[i][j]=0;
			}
		}
	}
	int mindist = INT_MAX;
	while(q.size()!=0)
	{
		auto it = q.front();
		q.pop();
		int currI = it.first;
		int currJ = it.second;
		for(int k=0;k<4;k++)
		{
			int newI = currI + dir[k][0];
			int newJ = currJ + dir[k][1];
		if(newI>=0 && newI<arr.size() && newJ >=0 && newJ <arr[0].size())
		{
			if(distance[newI][newJ]==-1)
			{
				distance[newI][newJ] = distance[currI][currJ] +1;
				owner[newI][newJ] = owner[currI][currJ]; 
				q.push({newI,newJ});
			}
			else
			{
				if (owner[newI][newJ] != owner[currI][currJ])
				{
					mindist = min (distance[newI][newJ]+distance[currI][currJ],mindist);
				}
			}
		}
		
		}
	}
	
	return mindist;
	
}

int main() {
	// your code goes here
	vector<vector<int>> arr = {{1, 0, 0, 0, 1},  
{1, 1, 0, 0, 0},  
{0, 0, 0, 0, 0},  
{0, 0, 1, 1, 1}};
int dis = findminDist (arr);
cout<<dis;
return 0;
}