#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 120;
int g[N][N];
int d[N][N];
int dx[4] = { 1,-1,0,0 }, dy[4] = { 0,0,1,-1 };
int n, m;
void bfs() {
memset(d, -1, sizeof d);
d[0][0] = 0;
queue<pair<int, int>> q;
q.push({ 0,0 });
while (!q.empty()) {
auto top = q.front();
for (int i = 0; i < 4; i++) {
int x = top.first + dx[i], y = top.second + dy[i];
if (x < n && x >= 0 && y >= 0 && y < m && d[x][y] == -1 && g[x][y] == 0) {
d[x][y] = d[top.first][top.second] + 1;
q.push({ x,y });
}
}
q.pop();
}
cout << d[n - 1][m - 1];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
bfs();
return 0;
}