#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>

using namespace std;

int h,w;
bool maze[502][502]={};
char c='.';

struct Kord { 
    int x; 
    int y; 
}; 
struct Polje { 
    Kord k;  
    int s;  
};
bool naTabli(int red, int kol) { 
    return (red >= 0) && (red <= h) && 
           (kol >= 0) && (kol <= w); 
} 
int slRed[]={1,1,-1,-1,0,0,-1,1};
int slKol[]={1,-1,1,-1,-1,1,0,0};
int konjR[]={2,2,1,1,-1,-1,-2,-2};
int konjK[]={1,-1,2,-2,2,-2,1,-1};
bool vecBio[502][502]={};
int bfs(Kord prvi, Kord posl){
    vecBio[prvi.x][prvi.y]=true;
    
    queue <Polje> q;
    q.push({prvi,1});
    
    while(!q.empty()){
        Polje polje = q.front();
        Kord kord = polje.k;
        q.pop();
        if(kord.x==posl.x && kord.y==posl.y) return polje.s;
        
        for(int i=0;i<8;i++){
            int x=kord.x+slRed[i];
            int y=kord.y+slKol[i];
            
            if(naTabli(x,y) && maze[x][y] && !vecBio[x][y]){
                vecBio[x][y]=true;
                q.push({{x,y},polje.s+1});
                //cout<<x<<" "<<y<<" "<<polje.s+1<<endl;
            }
        }
    }
    
    for(int i=1;i<=h;i++){
        for(int j=1;j<=w;j++){
            if(vecBio[i][j] && maze[i][j]){
                for(int k=0;k<8;k++){
                    int x=i+konjR[k];
                    int y=j+konjK[k];
                    if(naTabli(x,y) && maze[x][y] && !vecBio[x][y]){
                        //cout<<x<<" "<<y<<endl;
                        return bfs({x,y},posl)+6;
                    }
                }
            }
        }
    }
    
    return -1;
}

int bfsKONJ(Kord prvi, Kord posl){
    memset(vecBio, false, sizeof vecBio); 
    vecBio[prvi.x][prvi.y]=true;
    
    queue <Polje> q;
    q.push({prvi,0});
    
    while(!q.empty()){
        Polje polje = q.front();
        Kord kord = polje.k;
        //cout<<kord.x<<" "<<kord.y<<" "<<polje.s<<endl;
        q.pop();
        if(kord.x==posl.x && kord.y==posl.y) return polje.s;
        
        for(int i=0;i<8;i++){
            int x=kord.x+konjR[i];
            int y=kord.y+konjK[i];
            
            if(naTabli(x,y) && maze[x][y] && !vecBio[x][y]){
                vecBio[x][y]=true;
                q.push({{x,y},polje.s+1});
                //cout<<x<<" "<<y<<" "<<polje.s+1<<endl;
            }
        }
    }
    
    return -1;
}

int main() {
    cin>>h>>w;
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            cin>>c;
            if(c=='.')maze[i+1][j+1]=true;
        }
    }
    int r=bfs({1,1},{h,w})-1;
    //cout<<r<<endl;
    if(r==-1) return cout<<-1<<endl,0;
    if(r==0) return cout<<bfsKONJ({1,1},{h,w})+4<<endl,0;
    int k=bfsKONJ({1,1},{h,w});
    //cout<<k<<endl;
    if(k==-1){
        return cout<<r<<endl,0;
    }
    cout<<min(k+4,r)<<endl;
    return 0;
}