#include <bits/stdc++.h>
using namespace std;
int n, m, k, q, x, y, t, s, ans = 0x3f3f3f3f, a[510][510], maxx[510][510];
int main() {
  memset(a, 0x3f, sizeof(a));
  scanf("%d%d%d%d", &n, &m, &k, &q);
  for (int i = 1; i <= q; i++) scanf("%d%d%d", &x, &y, &t), a[x][y] = t;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m - k + 1; j++)
      for (int kk = 0; kk < k; kk++) maxx[i][j] = max(maxx[i][j], a[i][j + kk]);
  for (int i = 1; i <= n - k + 1; i++)
    for (int j = 1; j <= m - k + 1; j++) {
      s = 0;
      for (int kk = 0; kk < k; kk++) s = max(s, maxx[i + kk][j]);
      ans = min(ans, s);
    }
  if (ans > 1e9)
    cout << -1;
  else
    cout << ans;
  return 0;
}
