#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define pii pair<ll, ll>

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

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 search() {
   queue<pii> q;
   q.emplace(1, 1);
   ans[1][1] = 0;

   while (!q.empty()) {
      auto [i, j] = q.front();
      q.pop();

      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;
            q.emplace(ci, cj);
         }
      }

      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;
            q.emplace(ci, cj);
         }
      }
   }
}

int main() {
   cin >> n >> m;
   for (ll i = 0; i < n; i++) {
      string s;
      cin >> s;
      ans[i].resize(m, LLONG_MAX);
      a[i].resize(m);
      for (ll j = 0; j < m; j++) {
         a[i][j] = s[j] != '#';
      }
   }

   search();

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