#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N=1e4+10;
int q[N], hh,tt;
int d[N];
int n,m;
int bfs(int u)
{
memset(d,-1,sizeof d);
q[0]=u;
d[u]=0;
while(hh<=tt){
int t=q[hh++];
if(t==m) return d[t];
int j=t-1;
if(j>=0 && j<=10000 && d[j]==-1){
q[++tt]=j;
d[j]=d[t]+1;
}
j=t*2;
if(j>=0 && j<=10000 && d[j]==-1){
q[++tt]=j;
d[j]=d[t]+1;
}
}
}
void solve()
{
cin>>n>>m;
int cnt=0;
if(n>=m) cnt=n-m;
else {
cnt=bfs(n);
}
cout<<cnt<<'\n';
}
int main()
{
int T;
// cin>>T;
T=1;
while(T--){
solve();
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N=1e3+10;
int g[N][N],d[N][N];
PII q[N*N];
int n;
int bfs()
{
int hh=0,tt=0;
q[0]={1,1};
d[1][1]=1;//表示这个点已经到过,未到的点为0.最后结果多一步.
int dx[4]={-1,0,1,0}, dy[4]={0,1,0,-1};
while(hh<=tt)
{
auto t=q[hh++];
if(t.first ==n && t.second==n) return d[n][n]-1;
for(int i=0; i<4; i++){
int x=t.first+dx[i], y=t.second+dy[i];
if(x<1 || x>n || y<1 || y>n || g[x][y]==1){
if(i==0) for(int j=t.first; j<=n+1; j++){
if(g[j][y]==1 || j==n+1){
x=j-1;
break;
}
}
if(i==2) for(int j=t.first; j>=0; j--){
if(g[j][y]==1 || j==0) {
x=j+1;break;
}
}
if(i==1) for(int j=t.second; j>=0; j--){
if(g[x][j]==1 || j==0){
y=j+1; break;
}
}
if(i==3) for(int j=t.second; j<=n+1; j++){
if(g[x][j]==1 || j==n+1){
y=j-1;break;
}
}
}
if(d[x][y]==0){
d[x][y]=d[t.first][t.second]+1;
q[++tt]={x,y};
}
}
}
return -1;
}
void solve()
{
cin>>n;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
cin>>g[i][j];
}
}
cout<<bfs();
}
int main()
{
int T;
// cin>>T;
T=1;
while(T--){
solve();
}
return 0;
}