#include <bits/stdc++.h>
using namespace std;
long long inf = 1e18;
long long a[501][501];
long long n, m, k, q;
vector<pair<long long, pair<long long, long long> > > v;
bool fun(long long mid) {
  for (long long i = 0; i <= n; i++)
    for (long long j = 0; j <= m; j++) a[i][j] = 0;
  for (long long i = 0; i < (long long)v.size(); i++)
    if (v[i].first <= mid) a[v[i].second.first][v[i].second.second] = 1;
  for (long long i = 1; i < n + 1; i++)
    for (long long j = 1; j < m + 1; j++) a[i][j] += a[i][j - 1];
  for (long long j = 1; j < m + 1; j++)
    for (long long i = 1; i < n + 1; i++) a[i][j] += a[i - 1][j];
  for (long long i = k; i < n + 1; i++)
    for (long long j = k; j < m + 1; j++) {
      long long temp = a[i][j] - a[i - k][j] - a[i][j - k] + a[i - k][j - k];
      if (temp == k * k) return true;
    }
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n >> m >> k >> q;
  while (q--) {
    long long first, second, t;
    cin >> first >> second >> t;
    v.push_back({t, {first, second}});
  }
  long long l = 0, r = 1e9;
  while (l <= r) {
    long long mid = (l + r) / 2;
    if (fun(mid))
      r = mid - 1;
    else
      l = mid + 1;
  }
  if (fun(r + 1))
    cout << r + 1;
  else
    cout << -1;
  return 0;
}
