#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 1e3 + 10;
int n, k;
char mp[N][N];
bool vis[N][N][11];
int ans;
int dirx[4] = {0, 1, 0, -1};
int diry[4] = {1, 0, -1, 0};
struct node {
//结构体定义: x, y 位置, k:前剩余的无敌时间,
//step:到达这个位置的步数
int x, y, k, step;
node (int cx, int cy, int ck, int cs) {
x = cx, y = cy, k = ck, step = cs;
}
};
int bfs() {
queue<node> q;
//初始化(0, 0)点
vis[0][0][0] = true;
q.push(node(0, 0, 0, 0));
while (!q.empty()) {
//取出队头元素
node now = q.front();
q.pop();
//到达终点,返回答案
if (now.x == n - 1 && now.y == n - 1) {
return now.step;
}
//遍历上下左右四个点
for (int i = 0; i < 4; i++) {
int tox = now.x + dirx[i];
int toy = now.y + diry[i];
//越界或者为墙壁,不可达
if (tox < 0 || toy < 0 || tox >= n || toy >= n || mp[tox][toy] == '#') {
continue;
}
//(tox, toy)处有一个无敌道具, 且此处未访问过
if (mp[tox][toy] == '%' && !vis[tox][toy][k]) {
vis[tox][toy][k] = true;
q.push(node(tox, toy, k, now.step + 1));
} else {
//当前无敌,无论前方是陷阱还是道路都可走
if (now.k && !vis[tox][toy][now.k - 1]) {
vis[tox][toy][now.k - 1] = true;
q.push(node(tox, toy, now.k - 1, now.step + 1));
//当前不无敌, 而且前方为道路
} else if (mp[tox][toy] == '.' && !now.k && !vis[tox][toy][0]) {
vis[tox][toy][0] = true;
q.push(node(tox, toy, 0,now.step + 1));
}
}
}
}
//可到达的遍历完了但是仍然没有到达终点,表示不可达,返回-1
return -1;
}
int main() {
scanf("%d%d", &n, &k); //读入图的大小和无敌时间
for (int i = 0; i < n; i++) { //输入图
scanf("%s", mp[i]);
}
ans = bfs(); //调用BFS函数求解,无解时返回-1
cout << ans;
return 0;
}
/*
5 3
...XX
##%#.
...#.
.###.
.....
*/