#include <bits/stdc++.h>

using namespace std;

#define ll long long

ll n, m, di[] = {1, -1, 0, 0}, dj[] = {0, 0, 1, -1}, di1[] = {1, -1, 1, -1}, dj1[] = {1, 1, -1, -1};
vector<vector<ll>> ans;
vector<vector<bool>> a;

bool ok(ll i, ll j) {
    return i > 0 && j > 0 && i < n && j < m && a[i][j] && a[i - 1][j] && a[i][j - 1] && a[i - 1][j - 1];
}

void dijkstra() {
    priority_queue<pair<ll, pair<ll, ll>>, vector<pair<ll, pair<ll, ll>>>, greater<pair<ll, pair<ll, ll>>>> pq;
    ans[1][1] = 0;
    pq.push({0, {1, 1}});

    while (!pq.empty()) {
        ll dist = pq.top().first;
        ll i = pq.top().second.first;
        ll j = pq.top().second.second;
        pq.pop();

        if (dist > ans[i][j]) continue;

        for (ll k = 0; k < 4; k++) {
            ll ci = i + di1[k], cj = j + dj1[k];
            if (ok(ci, cj) && ans[ci][cj] > dist + 5) {
                ans[ci][cj] = dist + 5;
                pq.push({ans[ci][cj], {ci, cj}});
            }
        }

        for (ll k = 0; k < 4; k++) {
            ll ci = i + di[k], cj = j + dj[k];
            if (ok(ci, cj) && ans[ci][cj] > dist + 4) {
                ans[ci][cj] = dist + 4;
                pq.push({ans[ci][cj], {ci, cj}});
            }
        }
    }
}

int main() {
    cin >> n >> m;
    ans.assign(n, vector<ll>(m, LLONG_MAX));
    a.assign(n, vector<bool>(m));

    for (ll i = 0; i < n; i++) {
        string s;
        cin >> s;
        for (ll j = 0; j < m; j++) {
            a[i][j] = (s[j] != '#');
        }
    }

    dijkstra();

    cout << (ans[n - 1][m - 1] == LLONG_MAX ? -1 : ans[n - 1][m - 1]) << endl;
    return 0;
}