# include <bits/stdc++.h>

# define pb push_back
# define ff first
# define ss second
# define nl "\n"
# define sz(x) ((int)(x).size())
# define all(x) (x).begin(), (x).end()
# define deb(x) cerr << #x  << " = " << x << endl; 
# define pll pair <ll, ll>
# define pii pair <int, int>
 
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
 
const ll maxn = 2e5 + 7;
const ll inf = 2e18 + 0;
const ll mod = 1e9 + 7;
const ll dx[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const ll dy[] = {0, 0, -1, 1, -1, 1, 1, -1};
const ll cost[] = {4, 4, 4, 4, 5, 5, 5, 5};

using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

ll n, m;
vector < vector <ll> > dist;
vector < vector <char> > c;

bool in (int x, int y) {
	return (0 <= x && x < n && 0 <= y && y < m);
}

bool ok (int x, int y, int k) {
	vector <pii> v;
	v.pb({x, y});
	v.pb({x, y + 1});
	v.pb({x + 1, y});
	v.pb({x + 1, y + 1});
	for (auto [a, b] : v) {
		int tox = a + dx[k];
		int toy = b + dy[k];
		if (in(tox, toy) && c[tox][toy] == '.') continue;
		return 0;
	}
	return 1;
}

void ma1n () {
	cin >> n >> m;
	c.resize(n, vector<char>(m));
	dist.resize(n, vector<ll>(m, inf));
	for (ll i = 0; i < n; ++i) {
		for (ll j = 0; j < m; ++j) {
			cin >> c[i][j];
		}
	}
	set < pair <ll, pll> > st;
	dist[0][0] = 0;
	st.insert({dist[0][0], {0, 0}});
	while (!st.empty()) {
		int x = st.begin() -> ss.ff;
		int y = st.begin() -> ss.ss;
		st.erase(st.begin());
//		cout << x << ' ' << y << ' ' << dist[x][y] << nl;
		for (int k = 0; k < 8; ++k) {
			if (ok(x, y, k)) {
				int tox = x + dx[k];
				int toy = y + dy[k];
				if (dist[tox][toy] > dist[x][y] + cost[k]) {
					st.erase({dist[tox][toy], {tox, toy}});
					dist[tox][toy] = dist[x][y] + cost[k];
					st.insert({dist[tox][toy], {tox, toy}});
				}
			}
		}
	}
	if (dist[n - 2][m - 2] == inf) {
		cout << -1 << nl;
	}
	else {
		cout << dist[n - 2][m - 2] << nl;
	}
}
 
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
//  freopen("file.in", "r", stdin);
//  freopen("file.out", "w", stdout);
    int ttt = 1;
//  cin >> ttt;
    for (int test = 1; test <= ttt; ++test) {
//      cout << "Case " << test << ":" << '\n';
        ma1n();
    }
    return 0;
}
