#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;
for(int x = 1; x <= n; x++)
for(int y = 1; y <=m; y++)
cin>>mat[x][y];
solve(1,1);
(level[n][m] != 0)?cout<<level[n][m]<<endl:cout<<-1<<endl;
}
I2luY2x1ZGUgImJpdHMvc3RkYysrLmgiCnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgpjb25zdCBpbnQgbWF4biA9IDUwNTsKaW50IG4sbTsKI2RlZmluZSBpblJhbmdlKGksaikgKGkgPj0gMSBhbmQgaSA8PW4gYW5kIGogPj0gMSBhbmQgaiA8PSBtKQoKaW50IG1hdFttYXhuXVttYXhuXSx2aXNpdGVkW21heG5dW21heG5dLGxldmVsW21heG5dW21heG5dOwoKcXVldWU8IHBhaXI8aW50LGludD4gPlE7Cgp2b2lkIHNvbHZlKGludCBpLGludCBqKQp7CglRLnB1c2gobWFrZV9wYWlyKGksaikpOwoKCXdoaWxlKCFRLmVtcHR5KCkpewoKCQlpbnQgbm9kZTEgPSBRLmZyb250KCkuZmlyc3Q7CgkJaW50IG5vZGUyID0gUS5mcm9udCgpLnNlY29uZDsKCgkJUS5wb3AoKTsKCgkJLy8gcG9zaXRpb25zIGl0IGNhbiBnb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