#include "bits/stdc++.h"
using namespace std;
const int maxn = 505;
int n,m;
#define inRange(i,j) (i >= 1 and i <=n and j >= 1 and j <= m)
int mat[maxn][maxn],visited[maxn][maxn],level[maxn][maxn];
queue< pair<int,int> >Q;
void solve(int i,int j)
{
Q.push(make_pair(i,j));
while(!Q.empty()){
int node1 = Q.front().first;
int node2 = Q.front().second;
Q.pop();
// positions it can go to.
int a[] = {0,-mat[node1][node2],0,mat[node1][node2]} , b[] = {-mat[node1][node2],0,mat[node1][node2],0};
for(int x = 0; x < 4; x++){
int temp1 = node1 + a[x];
int temp2 = node2 + b[x];
if(inRange(temp1,temp2) and !visited[temp1][temp2]){
visited[temp1][temp2] = 1;
level[temp1][temp2] = level[node1][node2] + 1;
Q.push(make_pair(temp1,temp2));
}
}
}
}
int main()
{
visited[1][1] = 1;
cin>>n>>m;
string S;
for(int x = 1; x <= n; x++)
{
cin>>S;
for(int j=1;j<=m;j++)
{
mat[x][j]=S[j-1]-'0';
}
}
solve(1,1);
(visited[n][m] != 0)?cout<<level[n][m]<<endl:cout<<-1<<endl;
}
I2luY2x1ZGUgImJpdHMvc3RkYysrLmgiCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CiAKY29uc3QgaW50IG1heG4gPSA1MDU7CmludCBuLG07CiNkZWZpbmUgaW5SYW5nZShpLGopIChpID49IDEgYW5kIGkgPD1uIGFuZCBqID49IDEgYW5kIGogPD0gbSkKIAppbnQgbWF0W21heG5dW21heG5dLHZpc2l0ZWRbbWF4bl1bbWF4bl0sbGV2ZWxbbWF4bl1bbWF4bl07CiAKcXVldWU8IHBhaXI8aW50LGludD4gPlE7CiAKdm9pZCBzb2x2ZShpbnQgaSxpbnQgaikKewoJUS5wdXNoKG1ha2VfcGFpcihpLGopKTsKIAoJd2hpbGUoIVEuZW1wdHkoKSl7CiAKCQlpbnQgbm9kZTEgPSBRLmZyb250KCkuZmlyc3Q7CgkJaW50IG5vZGUyID0gUS5mcm9udCgpLnNlY29uZDsKIAoJCVEucG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