#include <iostream>
#include <limits.h>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
using namespace std;
using ll = long long;
#pragma region 상하좌우 / 위치
const pair<int, int> dir[]
{
{ 1, 0 },
{ -1, 0 },
{ 0, -1 },
{ 0, 1 },
};
#define _y first
#define _x second
#pragma endregion
#pragma region 빠른 입출력
#define FAST_IO() \
{\
ios::sync_with_stdio(false);\
cin.tie(NULL); \
cout.tie(NULL); \
}\
#pragma endregion
#define MAX 1001
struct sNode
{
int y, x, depth;
bool isBlock;
};
vector<vector<int>> graph;
int vis[MAX][MAX][2];
int n, m;
int bfs()
{
queue<sNode> q;
q.push({ 0, 0, 1, false });
vis[0][0][0] = true;
while (!q.empty())
{
auto cur = q.front();
q.pop();
int y = cur.y, x = cur.x, depth = cur.depth;
bool isBlock = cur.isBlock;
if (y == n - 1 &&
x == m - 1)
return depth;
// 4선 방향으로 bfs
for (int i = 0; i < 4; i++)
{
int ny = y + dir[i].first, nx = x + dir[i].second;
// 범위 체크
if (ny >= n ||
ny < 0 ||
nx >= m ||
nx < 0)
continue;
if (vis[ny][nx][isBlock])
continue;
// 아직 안뚫린 벽
if (graph[ny][nx])
{
if (!isBlock)
{
vis[ny][nx][1] = true;
q.push({ ny, nx, depth + 1, true });
}
}
else
{
vis[ny][nx][isBlock] = true;
q.push({ ny, nx, depth + 1, isBlock });
}
}
}
return -1;
}
int main()
{
FAST_IO();
cin >> n >> m;
graph.resize(n, vector<int>(m));
for (int i = 0; i < n; i++)
{
string val;
cin >> val;
for (int j = 0; j < m; j++)
graph[i][j] = val[j] - '0';
}
cout << bfs();
}