#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct Node {
int x, y, dist;
Node(int _x, int _y, int _dist): x(_x), y(_y), dist(_dist) {}
};
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int BFS(const vector<vector<int>>& maze, int n, int m) {
vector<vector<bool>> visited(n, vector<bool>(m, false));
queue<Node> q;
q.push(Node(0, 0, 0));
visited[0][0] = true;
while (!q.empty()) {
Node cur = q.front();
q.pop();
if (cur.x == n - 1 && cur.y == m - 1) {
return cur.dist;
}
for (int i = 0; i < 4; ++i) {
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] == 0 && !visited[nx][ny]) {
visited[nx][ny] = true;
q.push(Node(nx, ny, cur.dist + 1));
}
}
}
return -1; // Should not reach here if there is at least one valid path
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> maze(n, vector<int>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> maze[i][j];
}
}
int minMoves = BFS(maze, n, m);
cout << minMoves << endl;
return 0;
}