#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <string.h>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;

void dfs(int y, int x, int cnt);

int x_move[4] = {0, 0, 1, -1};
int y_move[4] = {1, -1, 0, 0};
int N, M;
int ans = 100001;
int **maze;
bool **visited;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    cin >> N >> M;

    maze = new int *[N];
    visited = new bool *[N];

    for (int i = 0; i < N; i++)
    {
        maze[i] = new int[M];

        visited[i] = new bool[M]{false};
    }

    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            scanf("%1d", &maze[i][j]);
        }
    }

    visited[0][0] = true;

    dfs(0, 0, 1);

    cout << ans;

    for (int i = 0; i < N; i++)
    {
        delete[] maze[i];
        delete[] visited[i];
    }

    delete[] maze;
    delete[] visited;

    return 0;
}

void dfs(int y, int x, int cnt)
{
    if (x == M - 1 && y == N - 1)
    {
        ans = min(ans, cnt);

        return;
    }

    for (int i = 0; i < 4; i++)
    {
        int next_x = x + x_move[i];
        int next_y = y + y_move[i];

        if (0 <= next_x && next_x < M && 0 <= next_y && next_y < N)
        {
            if (!visited[next_y][next_x] && maze[next_y][next_x] == 1)
            {
                visited[next_y][next_x] = true;

                dfs(next_y, next_x, cnt + 1);

                visited[next_y][next_x] = false;
            }
        }
    }
}