#include <bits/stdc++.h>

using namespace std;

#define int ll
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<double> vd;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pi> vp;
typedef vector<pl> vpl;

const int inf = 1e12;

int d[520][520];
pi p[520][520];

set<pair<int, pi>> s;
vp dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, -1}, {1, 1},{-1, -1}, {-1, 1}};
vp dirk = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};

bool ok(int x, int y, int n, int m){
	if (x >= 0 && y >= 0 && x < n && y < m)
		return 1;
	return 0;
}

int vis[520][520];
int a[520][520];

void dfs(int x, int y, int n, int m){
	vis[x][y] = 1;

	for (auto& i : dir){
		int u = i.first + x;
		int v = i.second + y;

		if (!ok(u,v,n,m)) continue;
		if (a[u][v] ==0 || vis[u][v]) continue;

		dfs(u,v,n,m);
	}

	for (auto& i : dirk){
		int u = i.first + x;
		int v = i.second + y;

		if (!ok(u,v,n,m)) continue;
		if (a[u][v] == 0 || vis[u][v]) continue;

		dfs(u,v,n,m);
	}
}

signed main()
{
	ios_base::sync_with_stdio(false); 
	cin.tie(nullptr); 
	cout.tie(nullptr); 
	cerr.tie(nullptr);	

	int n, m;
	cin >> n >> m;

	for (int i = 0; i < n; ++i){
		string tmp;
		cin >> tmp;
		for (int j = 0; j < m; ++j){
			d[i][j] = inf;
			if (tmp[j] == '.')
				a[i][j] = 1;
			else
				a[i][j] = 0;
		}
	}

	dfs(0,0,n,m);

	if (!vis[n - 1][m - 1]) return cout << "-1\n", 0;

	d[0][0] = 0;

	s.insert({{d[0][0]}, {0, 0}});

	while (!s.empty()){
		pi v = s.begin()->second;
		s.erase(s.begin());

		for (auto& i : dir){
			int x = v.first + i.first;
			int y = v.second + i.second;

			if (!ok(x,y,n,m)) continue;
			if (a[x][y] == 0) continue;

			if (d[v.first][v.second] + 1 < d[x][y]){
				s.erase({d[x][y], {x, y}});
				d[x][y] = d[v.first][v.second] + 1;
				p[x][y] = v;
				s.insert({d[x][y], {x, y}});
			}
		}
	}

	if (d[n - 1][m - 1] == inf)
		cout << "-1\n";
	else
		cout << d[n - 1][m - 1] << '\n';
}