#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;
const int mxn = 250000;
#define inf 0x3f3f3f3f
inline int son(int p,int x){
return (p<<2)-2+x;
}
int n,m;
struct Interval:public pair<short ,short >{
#define l first
#define r second
Interval(short a, short b):pair<short ,short >(a,b){}
short mid(){
return ((r-l)>>1)+l;
}
short length(){
return r-l+(short)1;
}
Interval left(){
return Interval(l,mid());
}
Interval right(){
return Interval(mid()+(short)1,r);
}
bool in(int L,int R){
return l <= L and R <= r;
}
bool in(const Interval&temp){
return in(temp.l,temp.r);
}
bool intersect(const Interval &k){
return !( l > k.r || r < k.l );
}
void show(){
cerr<<l<<" "<<r<<"\n";
}
};
int plant[505][505];
int val[mxn<<2];
void pushUp(int rt){
for(int i = 0 ; i < 4 ; ++i){
val[rt] = max(val[rt],val[son(rt,i)]);
}
}
void buildTree(int rt,Interval x,Interval y){
if(x.length() <= 0 or y.length() <=0)return;
if(x.length()==1 and y.length() == 1){
val[rt] = plant[x.l][y.l];
return;
}
for(int i = 0; i < 4 ; ++i){
buildTree(son(rt,i) , (i&1)?x.right():x.left(),(i&2)?y.right():y.left());
}
pushUp(rt);
}
Interval tarx(0,0),tary(0,0);
int Query(int rt,Interval x,Interval y){
if(tarx.in(x) and tary.in(y)){
return val[rt];
}
if(!tary.intersect(y) or !tarx.intersect(x))return 0;
int ret = 0;
for(int i = 0 ; i < 4 ; ++i){
ret = max(ret,Query(son(rt,i) , (i&1)?x.right():x.left(),(i&2)?y.right():y.left()));
}
return ret;
}
int Query(short begx, short begy,int k){
tarx = Interval(begx,begx+(short)(k-1));
tary = Interval(begy,begy+(short)(k-1));
return Query(1,Interval(1,n),Interval(1,m));
}
int main(){
ios::sync_with_stdio(false);
cin>>n>>m;
int k,t,x,y,a;
cin>>k>>t;
memset(plant,0x3f, sizeof(plant));
while (t--){
cin>>x>>y>>a;
plant[x][y] = a;
}
int ans = inf;
buildTree(1,Interval(1,n),Interval(1,m));
for(int i = 1 ; i <= n-k+1; ++i){
for(int j = 1 ; j <= m-k+1; ++j){
ans = min(ans,Query(i,j,k));
}
}
if(ans!=inf){
cout<<ans;
}else cout<<-1;
}