#include
#include
using namespace std;
int main() {
int redovi, koloni;
cin >> redovi >> koloni;
char lavirint[redovi][koloni];
int poseteno[redovi][koloni], poseteno2[redovi][koloni], poseteno3[redovi][koloni];
int si, sj;
for(int i = 0; i < redovi; i++) {
for(int j = 0; j < koloni; j++) {
cin >> lavirint[i][j];
if(lavirint[i][j] == 'P') {
si = i;
sj = j;
}
poseteno[i][j] = 0;
poseteno2[i][j] = 0;
poseteno3[i][j] = 0;
}
}
int direction_i[] = {+1, -1, 0, 0};
int direction_j[] = {0, 0, +1,-1};
int direction2_i[] = {+2, -2, 0, 0};
int direction2_j[] = {0, 0, +2, -2};
int direction3_i[] = {+3, -3, 0, 0};
int direction3_j[] = {0, 0, +3, -3};
queue Q;
Q.push(si);
Q.push(sj);
Q.push(1);
Q.push(0);
poseteno[si][sj] = 1;
while(Q.size() > 0) {
int ci = Q.front();
Q.pop();
int cj = Q.front();
Q.pop();
int tip_cekor = Q.front();
Q.pop();
int cekor = Q.front();
Q.pop();
cout << ci << " " << cj << endl;
if(lavirint[ci][cj] == 'K') {
cout << cekor << endl;
break;
}
if(tip_cekor == 1) {
for(int i = 0; i < 4; i++) {
int ti = ci + direction_i[i];
int tj = cj + direction_j[i];
if(ti >= 0 and ti < redovi and tj >= 0 and tj < koloni and lavirint[ti][tj] != '#' and poseteno[ti][tj] == 0) {
Q.push(ti);
Q.push(tj);
Q.push(2);
Q.push(cekor + 1);
poseteno[ti][tj] = 1;
}
}
}
else if(tip_cekor == 2) {
for(int i = 0; i < 4; i++) {
int ti = ci + direction_i[i];
int tj = cj + direction_j[i];
if(ti >= 0 and ti < redovi and tj >= 0 and tj < koloni and lavirint[ti][tj] != '#') {
ti = ci + direction2_i[i];
tj = cj + direction2_j[i];
if(ti >= 0 and tj < redovi and tj >= 0 and tj < koloni and lavirint[ti][tj] != '#' and poseteno2[ti][tj] == 0) {
Q.push(ti);
Q.push(tj);
Q.push(3);
Q.push(cekor + 1);
poseteno2[ti][tj] = 1;
}
}
}
}
else if(tip_cekor == 3) {
for(int i = 0; i < 4; i++) {
int ti = ci + direction_i[i];
int tj = cj + direction_j[i];
if(ti >= 0 and ti < redovi and tj >= 0 and tj < koloni and lavirint[ti][tj] != '#') {
ti = ci + direction2_i[i];
tj = cj + direction2_j[i];
if(ti >= 0 and ti < redovi and tj >= 0 and tj < koloni and lavirint[ti][tj] != '#') {
ti = ci + direction3_i[i];
tj = cj + direction3_j[i];
if(ti >= 0 and ti < redovi and tj >= 0 and tj < koloni and lavirint[ti][tj] != '#' and poseteno3[ti][tj] == 0) {
Q.push(ti);
Q.push(tj);
Q.push(1);
Q.push(cekor + 1);
poseteno3[ti][tj] = 1;
}
}
}
}
}
}
return 0;
}
/*
4 7
P......
#.##K..
.#.#..#
##..##.
**/