#include<queue>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<string.h>
using namespace std;
#define N 30
char map[N][N];
struct node {
double t;
int x,y,f;
friend bool operator<(node a,node b) {
return a.t>b.t;
}
};
double min(double a,double b) {
return a>b?b:a;
}
double max(double a,double b) {
return a>b?a:b;
}
int px,py,bx,by,n,m,visit[N][N],visits[N][N];
int dis[4][2]={1,0,-1,0,0,1,0,-1};
double ans;
int judge(int x,int y) {
if(x>=1&&x<=n&&y>=1&&y<=m&&map[x][y]!='X')
return 1;
return 0;
}
void bfs() {
int i,tstart,tend;
memset(visit,0,sizeof(visit));
memset(visits,0,sizeof(visits));//第二个数组用来记录获得加速器后的状态情况
priority_queue<node>q;
node cur,next;
cur.x=px;cur.y=py;
cur.t=0;
cur.f=0;
visit[px][py]=1;
q.push(cur);
while(!q.empty()) {//对时间用优先队列
cur=q.top();
q.pop();
if(cur.x==bx) {//
tstart=min(cur.y,by);
tend=max(cur.y,by);
for(i=tstart;i<=tend;i++)
if(map[cur.x][i]=='X')
break;
if(i==tend+1)
ans=min(ans,(tend-tstart)*0.2+cur.t);
}
if(cur.y==by) {//判断伸舌头是否能吃掉
tstart=min(cur.x,bx);
tend=max(cur.x,bx);
for(i=tstart;i<=tend;i++)
if(map[i][cur.y]=='X')
break;
if(i==tend+1)
ans=min(ans,(tend-tstart)*0.2+cur.t);
}
for(i=0;i<4;i++) {
int x=next.x=cur.x+dis[i][0];
int y=next.y=cur.y+dis[i][1];
if(judge(x,y)) {
if(cur.f==0&&visit[x][y])continue;//
if(cur.f&&visits[x][y])continue;//有一个不符合就跳过
if(x==bx&&y==by) {//出口
ans=min(ans,cur.t+0.2);
printf("%.1f\n",ans);
return ;
}
if(cur.f==1) {
next.t=cur.t+0.5;
next.f=1;
}
else {
next.t=cur.t+1;
next.f=0;
}
if(map[x][y]=='S') {
next.f=1;
map[x][y]='.';
}
if(next.f==1)
visits[x][y]=1;
else
visit[x][y]=1;
q.push(next);
}
}
}
printf("-1\n");
return ;
}
int main() {
int i,j;
while(scanf("%d%d",&n,&m)!=EOF) {
for(i=1;i<=n;i++)
scanf("%s",map[i]+1);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++) {
if(map[i][j]=='P')
px=i,py=j;
if(map[i][j]=='B')
bx=i,by=j;
}
ans=999999999;
bfs();
}
return 0;
}