#include<bits/stdc++.h>
#define source 2*n*m+1
#define conflu 2*n*m+2
#define int long long
using namespace std;
inline int read(){
int res=0;
char c;
bool zf=0;
while(((c=getchar())<'0'||c>'9')&&c!='-');
if(c=='-')zf=1;
else res=c-'0';
while((c=getchar())>='0'&&c<='9')res=(res<<3)+(res<<1)+c-'0';
if(zf)return -res;
return res;
}
int n,m,xiyi;
int Next[20000005],to[20000005],head[20000005],dis[20000005],cur[20000005],tot=-1;
inline void add_edge(int x,int y,int c){
tot++;
Next[tot]=head[x];head[x]=tot;
to[tot]=y;
dis[tot]=c;
return;
}
inline void create(){
int d=read();
for(register int i=1;i<=n;i++)
for(register int j=1;j<=m;j++)
for(register int k=i;k<=n;k++)
for(register int l=j;l<=m;l++)
if((k>i||l>j)&&((k-i)*(k-i)+(l-j)*(l-j))<=d*d)
add_edge(((i-1)*m+j)+n*m,(k-1)*m+l,1e9),add_edge((k-1)*m+l,((i-1)*m+j)+n*m,0),add_edge(((k-1)*m+l)+n*m,(i-1)*m+j,1e9),add_edge((i-1)*m+j,((k-1)*m+l)+n*m,0);
for(register int i=1;i<=n;i++)
for(register int j=1;j<=m;j++)
if(i<=d||j<=d||n-i+1<=d||m-j+1<=d){
add_edge(((i-1)*m+j)+n*m,conflu,1),add_edge(conflu,((i-1)*m+j)+n*m,0);
}
char c;
for(register int i=1;i<=n;i++)
for(register int j=1;j<=m;j++){
while((c=getchar())<'0'||c>'9');
if(c!='0')add_edge((i-1)*m+j,((i-1)*m+j)+n*m,c-'0'),add_edge(((i-1)*m+j)+n*m,(i-1)*m+j,0);
}
for(register int i=1;i<=n;i++)
for(register int j=1;j<=m;j++){
while((c=getchar())!='L'&&c!='.');
if(c=='L')add_edge(source,(i-1)*m+j,1),add_edge((i-1)*m+j,source,0),xiyi++;
}
return;
}
int dep[100005];
inline bool bfs(){
memset(dep,-1,sizeof(dep));
dep[source]=0;
queue<int>Q;Q.push(source);
while(!Q.empty()){
int x=Q.front();Q.pop();
for(register int i=head[x];i;i=Next[i]){
int v=to[i];
if(dis[i]&&dep[v]==-1){
dep[v]=dep[x]+1;
Q.push(v);
}
}
}
if(dep[conflu]!=-1)return 1;
return 0;
}
int maxflow;
int dfs(int now,int flow){
if(flow==0)return 0;
if(now==conflu)return flow;
int tflow=flow,tmp;
for(register int i=cur[now];i;i=Next[i]){
cur[now]=i;
int v=to[i];
if(dis[i]&&dep[v]==dep[now]+1)
if(tmp=dfs(v,min(flow,dis[i]))){
flow-=tmp;
dis[i]-=tmp;dis[i^1]+=tmp;
if(!flow)break;
}
}
return tflow-flow;
}
inline void dinic(){
int tmp;
while(bfs()){
for(register int i=1;i<=conflu;i++)cur[i]=head[i];
while(tmp=dfs(source,2e10))
maxflow+=tmp;
}
return;
}
signed main(){
n=read();m=read();
create();dinic();
cout<<xiyi-maxflow<<'\n';
return 0;
}