#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}};

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

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

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

	int a[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;
		}
	}

	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';
}