#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
string board[50];
int height[50][50], N, CNT=0;
int dx[8]={0, 0, 1, -1, 1, -1, 1, -1};
int dy[8]={1, -1, 0, 0, 1, -1, -1, 1};
bool isRange(int x, int y ){
return x>=0 && x<N && y>=0 && y<N;
}
int bfs(pair<int, int> start, vector<int>& h, int k) {
for(auto &low:h) {
if(height[start.first][start.second]>low+k || height[start.first][start.second]<low)
continue;
queue<pair<int, int>> q;
vector<vector<bool>> discovered(N, vector<bool>(N, false));
q.push(start);
discovered[start.first][start.second] = true;
int cnt = CNT;
while (!q.empty()) {
pair<int, int> here = q.front();
q.pop();
if (board[here.first][here.second] == 'K')
cnt--;
if (cnt == 0)
return true;
for (int i = 0; i < 8; ++i) {
pair<int, int> there = {here.first + dx[i], here.second + dy[i]};
if(!isRange(there.first, there.second))
continue;
if (discovered[there.first][there.second])
continue;
if (height[there.first][there.second]>low+k || height[there.first][there.second]<low)
continue;
q.push(there);
discovered[there.first][there.second] = true;
}
}
}
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin>>N;
pair<int, int> start;
vector<int> h;
for(int i=0; i<N; ++i) {
cin>>board[i];
}
for(int i=0; i<N; ++i) {
for(int j=0; j<N; ++j) {
cin>>height[i][j];
h.emplace_back(height[i][j]);
if(board[i][j]=='P')
start={i, j};
else if(board[i][j]=='K')
CNT++;
}
}
sort(h.begin(), h.end());
int low=-1, hi=1000000;
while(low+1<hi) {
int mid=(low+hi)/2;
if(bfs(start, h, mid))
hi=mid;
else
low=mid;
}
cout<<hi;
return 0;
}