#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 5e2 + 10;
const long long INF = 1e12 + 10;
long long a[MAXN][MAXN];
long long b[MAXN][MAXN];
long long ps[MAXN][MAXN];
long long n, m, k, q;
bool ok(long long f) {
  for (long long i = 0; i <= n; i++) {
    for (long long j = 0; j <= m; j++) {
      b[i][j] = (a[i][j] <= f);
    }
  }
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= m; j++) {
      ps[i][j] = ps[i - 1][j] + ps[i][j - 1] - ps[i - 1][j - 1] + b[i][j];
    }
  }
  for (long long i = k; i <= n; i++) {
    for (long long j = k; j <= m; j++) {
      if (ps[i][j] - ps[i - k][j] - ps[i][j - k] + ps[i - k][j - k] ==
          (k * k)) {
        return true;
      }
    }
  }
  return false;
}
int main() {
  ios_base ::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> m >> k >> q;
  for (long long i = 0; i <= n; i++) {
    for (long long j = 0; j <= m; j++) {
      a[i][j] = INF;
    }
  }
  for (long long i = 0; i < q; i++) {
    long long x, y, t;
    cin >> x >> y >> t;
    a[x][y] = t;
  }
  long long l = -1, r = INF;
  while (true) {
    if (r - l == 1) {
      cout << (r == INF ? -1 : r);
      return 0;
    }
    long long mid = (l + r) / 2;
    if (ok(mid)) {
      r = mid;
    } else {
      l = mid;
    }
  }
}
