#include <iostream>
#include <unordered_map>

using namespace std;

#define ll long long

struct pair_hash {
    inline size_t operator()(const pair<ll,ll> & v) const {
        return v.first * 31 + v.second;
    }
};

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

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

void dfs(ll i, ll j) {
    if (ans[{i, j}] > ans[{n - 1, m - 1}]) return;
    for (ll k = 0; k < 4; k++) {
        ll ci = i + di1[k], cj = j + dj1[k];
        if (ok(ci, cj) && ans[{ci, cj}] > ans[{i, j}] + 5) {
            ans[{ci, cj}] = ans[{i, j}] + 5;
            dfs(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}] > ans[{i, j}] + 4) {
            ans[{ci, cj}] = ans[{i, j}] + 4;
            dfs(ci, cj);
        }
    }
}

int main() {
    cin >> n >> m;
    string s;
    for (ll i = 0; i < n; i++) {
        cin >> s;
        for (ll j = 0; j < m; j++) {
            ans[{i, j}] = 999999999;
            a[{i, j}] = (s[j] != '#');
        }
    }
    ans[{1, 1}] = 0;
    dfs(1, 1);
    cout << (ans[{n - 1, m - 1}] == 999999999 ? -1 : ans[{n - 1, m - 1}]) << endl;
    return 0;
}