#include <bits/stdc++.h>
using namespace std;
int input() {
  int res = 0, m = 1;
  char c = ' ';
  while (c < '0' && c != '-') c = getchar();
  if (c == '-') m = -1, c = getchar();
  while (c >= '0') res = res * 10 + (c - '0'), c = getchar();
  return res * m;
}
const int N = 501;
int n, k, lft[N], l_siz, fl[N], rht[N], r_siz, fr[N];
void shift() {
  while (r_siz) lft[l_siz] = rht[--r_siz], ++l_siz;
  if (l_siz) fl[0] = lft[0];
  for (int i = 1; i < l_siz; ++i) fl[i] = max(fl[i - 1], lft[i]);
}
void push(int x) {
  int prev = (r_siz ? fr[r_siz - 1] : 0);
  rht[r_siz] = x, fr[r_siz] = max(prev, x), ++r_siz;
}
void pop() {
  if (!l_siz) shift();
  --l_siz;
}
int get() {
  int res = 0;
  if (l_siz) res = fl[l_siz - 1];
  if (r_siz) res = max(res, fr[r_siz - 1]);
  return res;
}
int a[N][N], mx[N][N], ans = 2e9;
int main() {
  int n = input(), m = input(), k = input();
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) a[i][j] = 2e9;
  for (int q = input(); q; --q) {
    int i = input() - 1, j = input() - 1, t = input();
    a[i][j] = t;
  }
  for (int j = 0; j < m; ++j) {
    for (int i = 0; i < k; ++i) push(a[i][j]);
    mx[0][j] = get();
    for (int i = 0; i < n - k; ++i) {
      pop(), push(a[i + k][j]);
      mx[i + 1][j] = get();
    }
    while (l_siz + r_siz) pop();
  }
  for (int i = 0; i <= n - k; ++i) {
    for (int j = 0; j < k; ++j) push(mx[i][j]);
    ans = min(ans, get());
    for (int j = 0; j < m - k; ++j) {
      pop(), push(mx[i][j + k]);
      ans = min(ans, get());
    }
    while (l_siz + r_siz) pop();
  }
  cout << (ans == 2e9 ? -1 : ans);
}
