#include<stdlib.h>
#include<stdio.h>
#include<queue>
using namespace std;

int solve(char** polje, int** visited, int** levels, int x, int y, int n,int m, int p1, int p2){
    queue <pair<int,int> > wait;
    int state=0;
    wait.push(make_pair(x,y));
    while(polje[wait.front().first][wait.front().second]!='P'  && !wait.empty()){
        x=wait.front().first;
        y=wait.front().second;
        if(x+1<n && polje[x+1][y] !='#' && visited[x+1][y]==0){
            visited[x+1][y]=1;
            wait.push(make_pair(x+1,y));
            levels[x+1][y]  = levels[x][y]+1;
        }
        if(x-1>=0 && polje[x-1][y] !='#' && visited[x-1][y]==0){
            visited[x-1][y]=1;
            wait.push(make_pair(x-1,y));
            levels[x-1][y]  = levels[x][y]+1;

        }
        if(y+1<m && polje[x][y+1] !='#' && visited[x][y+1]==0){
            visited[x][y+1]=1;
            wait.push(make_pair(x,y+1));
            levels[x][y+1]  = levels[x][y]+1;
        }
        if(y-1>=0 && polje[x][y-1] !='#' && visited[x][y-1]==0){
            visited[x][y-1]=1;
            wait.push(make_pair(x,y-1));
            levels[x][y-1] = levels[x][y]+1;
        }
        if(x+1<n && y-1>=0 && polje[x+1][y-1] !='#' && visited[x+1][y-1]==0){
            visited[x+1][y-1]=1;
            wait.push(make_pair(x+1,y-1));
            levels[x+1][y-1]  = levels[x][y]+1;
        }
        if(x+1<n && y+1<m && polje[x+1][y+1] !='#' && visited[x+1][y+1]==0){
            visited[x+1][y+1]=1;
            wait.push(make_pair(x+1,y+1));
            levels[x+1][y+1]  = levels[x][y]+1;
        }
        if(x-1>=0 && y-1>=0 && polje[x-1][y-1] !='#' && visited[x-1][y-1]==0){
            visited[x-1][y-1]=1;
            wait.push(make_pair(x-1,y-1));
            levels[x-1][y-1]  = levels[x][y]+1;
        }
        if(x-1>=0 && y+1<m && polje[x-1][y+1] !='#' && visited[x-1][y+1]==0){
            visited[x-1][y+1]=1;
            wait.push(make_pair(x-1,y+1));
            levels[x-1][y+1]  = levels[x][y]+1;
        }
        
        wait.pop();
    }
   return levels[p1][p2];
}

int main()
{
  int n,m,x,y;
  int p1,p2;
  int br=0;
  scanf("%d%d",&n,&m);


  char** polje = new char*[n];
  int** visited = new int*[n];
  int** levels = new int*[n];
   
  for(int i=0; i<n; i++){
    polje[i] = new char[m];
    visited[i] = (int*)calloc(m, sizeof(int));
    levels[i] = (int*)calloc(m, sizeof(int));
  }

  for(int i=0; i<n; i++)
    for(int j=0; j<m; j++)
      scanf(" %c",&polje[i][j]);
      
  polje[n-1][m-1] = 'P';
  int p=solve(polje,visited,levels,0,0,n,m,n-1,m-1);
  if(p==0)
    printf("%d",-1);
  else
    printf("%d",p);
}