#include<bits/stdc++.h>
using namespace std;
const int N=1e3+100;
int n,m,work[N],temp,ans;
char chr[5005][5005];
bool vis[5005][5005];
int dx[]={-1,0,0,1};
int dy[]={0,1,-1,0};
struct Edge
{
int x,y,step;
};queue<Edge> q;
inline void inti()
{
for(int i=0;pow(2,i)<=1000;i++)
{
work[++temp]=pow(2,i);
}
return ;
}
inline bool check(int x,int y)
{
if(x>=1 and x<=n and y>=1 and y<=m and vis[x][y]==false)
{
return true;
}
return false;
}
inline void BFS(int x,int y)
{
q.push(Edge{x,y,0});vis[x][y]=true;
while(!q.empty())
{
Edge head=q.front();q.pop();
if(chr[head.x][head.y]=='#')
{
ans=head.step;
return ;
}
for(int i=0;i<4;i++)
{
for(int j=1;j<=temp;j++)
{
int xx=dx[i]*work[j]+head.x,yy=dy[i]*work[j]+head.y;
if(check(xx,yy)==true)
{
if(chr[xx][yy]=='X' or chr[xx][yy]=='.')
{
break;
}
q.push(Edge{xx,yy,head.step+1});vis[xx][yy]=true;
}
}
}
}
ans=-1;
return ;
}
signed main(void)
{
inti();
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>chr[i][j];
}
}
BFS(1,1);
printf("%d\n",ans);
return 0;
}