#include <bits/stdc++.h>
using namespace std;
int t[510][510], sum[510][510], n, m, k, q;
int check(int time) {
  memset(sum, 0, sizeof(sum));
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (time >= t[i][j] && t[i][j] != -1) {
        sum[i][j] = 1;
      }
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      sum[i][j] += sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1];
      if (i >= k && j >= k &&
          (sum[i][j] - sum[i - k][j] - sum[i][j - k] + sum[i - k][j - k] >=
           k * k)) {
        return 1;
      }
    }
  }
  return 0;
}
int main() {
  ios::sync_with_stdio(0);
  cin >> n >> m >> k >> q;
  int x, y, in;
  memset(t, -1, sizeof(t));
  for (int i = 1; i <= q; i++) {
    cin >> x >> y >> in;
    t[x][y] = in;
  }
  int l = 0, r = 1e9 + 1, mid;
  while (l < r) {
    mid = (l + r) / 2;
    if (check(mid))
      r = mid;
    else
      l = mid + 1;
  }
  if (r == 1e9 + 1)
    cout << -1;
  else
    cout << r;
  cout << endl;
}
