#include<bits/stdc++.h>
using namespace std;
struct node
{
int x;
int y;
int step;
bool wd;
int step2;
};
int n,k;
char mp[1005][1005];
int vis[1005][1005];
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
bool flag=1;
queue<node> q;
node s,t;
void bfs()
{
s.x=0;
s.y=0;
t.x=t.y=-1;
s.step=0;
if(s.x=='%')
{
s.wd=1;
s.step2=k;
}
else
{
s.wd=0;
s.step2=0;
}
q.push(s);
while(!q.empty())
{
node tmp=q.front();
q.pop();
if(tmp.x==t.x&&tmp.y==t.y)
{
cout<<tmp.step;
flag=0;
return;
}
for(int i=0;i<4;i++)
{
node a;
a.x=tmp.x+dx[i];
a.y=tmp.y+dy[i];
a.step=tmp.step+1;
if(a.step2)
{
a.step2--;
}
else
{
a.wd=0;
}
if(a.x>=0&&a.y>=0&&vis[a.x][a.y]==0&&mp[a.x][a.y]!='#')
{
if(mp[a.x][a.y]=='X')
{
if(a.wd)
{
q.push(a);
if(mp[a.x][a.y]=='%')
{
a.wd=1;
a.step2=k;
}
}
}
else
{
q.push(a);
}
}
}
}
}
int main()
{
cin>>n>>k;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>mp[i][j];
}
}
bfs();
if(flag)
{
cout<<-1;
}
return 0;
}