#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
const int INF = 0x3f3f3f3f;
int n, m, k, q;
int mp[N][N], sum[N][N];
bool legal(int t) {
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      if (mp[i][j] && mp[i][j] <= t)
        sum[i][j] = 1;
      else
        sum[i][j] = 0;
    }
  }
  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];
    }
  }
  for (int i = k; i <= n; ++i) {
    for (int j = k; j <= m; ++j) {
      long long tmp =
          sum[i][j] - sum[i - k][j] - sum[i][j - k] + sum[i - k][j - k];
      if (tmp == k * k) {
        return true;
      }
    }
  }
  return false;
}
int main() {
  ios::sync_with_stdio(0);
  cin >> n >> m >> k >> q;
  for (int i = 1, x, y; i <= q; ++i) {
    cin >> x >> y;
    cin >> mp[x][y];
    mp[x][y]++;
  }
  int l = 1, r = (int)1e9 + 10;
  while (l < r) {
    int mid = l + r >> 1;
    if (legal(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  if (legal(r))
    cout << r - 1 << endl;
  else
    puts("-1");
  return 0;
}
