#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define f first
#define s second
#define boost ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define gcd __gcd
#define endl "\n"
#define ld long double
#define int ll
int n, m, i, j, x, y, nx, ny;
pair<pair<int, int>, int> dr[] = {{{-1, 0}, 4}, {{0, -1}, 4}, {{0, 1}, 4}, {{1, 0}, 4}, {{-1, -1}, 5}, {{-1, 1}, 5}, {{1, -1}, 5}, {{1, 1}, 5}};

main() {
  cin.tie(0)->sync_with_stdio(0);
  cin >> n >> m;
  char a[n + 1][m + 1], b[n][m];
  int d[n + 1][m + 1];
  for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) cin >> a[i][j];
  for (i = 1; i < n; i++) {
    for (j = 1; j < m; j++) {
      if (a[i][j] == '.' && a[i][j + 1] == '.' && a[i + 1][j] == '.' && a[i + 1][j + 1] == '.') b[i][j] = '.';
      else b[i][j] = '#';
      //cout << b[i][j];
      d[i][j] = 1e18;
    }
    //cout << "\n";
  }
  set<pair<int, pair<int, int>>> q;
  d[1][1] = 0;
  q.insert({0, {1, 1}});
  while (q.size()) {
    x = (*q.begin()).second.first, y = (*q.begin()).second.second;
    q.erase(q.begin());
    for (int i = 0; i < 12; i++) {
      nx = x + dr[i].first.first, ny = y + dr[i].first.second;
      if (nx < 1 || ny < 1 || nx >= n || ny >= m || b[nx][ny] == '#') continue;
      if (dr[i].first.first == -2 && a[x - 1][y] == '#') continue;
      if (dr[i].first.first == 2 && a[x + 1][y] == '#') continue;
      if (dr[i].first.second == -2 && a[x][y - 1] == '#') continue;
      if (dr[i].first.second == 2 && a[x][y + 1] == '#') continue;
      if (d[nx][ny] > d[x][y] + dr[i].second) {
        q.erase({d[nx][ny], {nx, ny}});
        d[nx][ny] = d[x][y] + dr[i].second;
        q.insert({d[nx][ny], {nx, ny}});
      }
    }
  }
  // for (i = 1; i < n; i++) {
  //   for (j = 1; j < m; j++) {
  //     cout << d[i][j] << " ";
  //   }
  //   cout << "\n";
  // }
  if (d[n - 1][m - 1] < 1e18) cout << d[n - 1][m - 1];
  else cout << -1;
}
