#include <bits/stdc++.h> 
using namespace std; 

int ROW, COL;

struct Point 
{ 
    int x; 
    int y; 
}; 

struct queueNode 
{ 
    Point pt;
    int dist;
}; 

bool isValid(int row, int col) 
{ 
    return (row >= 0) && (row < ROW) && 
           (col >= 0) && (col < COL); 
} 

int main() 
{ 
  
    int rowNum[] = {-1, 0, 0, 1, 1, 1, -1, -1}; 
    int colNum[] = {0, -1, 1, 0, 1, -1, 1, -1}; 
    
    cin >> ROW >> COL;

    int mat[ROW][COL];
    string c;
    for(int i = 0; i < ROW; i++){
        cin >> c; 
        for(int j = 0; j < COL; j++){
            if(c[j] == '.') mat[i][j] = 1;
            else mat[i][j] = 0;
        }
    }
  
    Point src = {0, 0}; 
    Point dest = {ROW-1, COL-1}; 

    if (!mat[src.x][src.y] || !mat[dest.x][dest.y]) {
        cout << -1; 
        return 0;
    }
  
    bool visited[ROW][COL]; 
    memset(visited, false, sizeof visited); 
      
    visited[src.x][src.y] = true; 
  
    queue<queueNode> q; 
       
    queueNode s = {src, 0}; 
    q.push(s);
  
    while (!q.empty()) 
    { 
        queueNode curr = q.front(); 
        Point pt = curr.pt; 
  
        if (pt.x == dest.x && pt.y == dest.y) {
            cout << curr.dist; 
            return 0;
        }
  
        q.pop(); 
  
        for (int i = 0; i < 8; i++) 
        { 
            int row = pt.x + rowNum[i]; 
            int col = pt.y + colNum[i]; 
              
            if (isValid(row, col) && mat[row][col] &&  
               !visited[row][col]) 
            { 
                visited[row][col] = true; 
                queueNode Adjcell = { {row, col}, 
                                      curr.dist + 1 }; 
                q.push(Adjcell); 
            } 
        } 
    } 
  
    cout << -1;

    return 0; 
}