#include <bits/stdc++.h>
using namespace std;
int n, i, j, k, x, y, z, m, q, w, h, l, timer;
int a[505][505], pa[505][505];
pair<int, pair<int, int> > queries[250500];
int main() {
  cin >> n >> m >> k >> q;
  for (i = 0; i < q; i++) {
    scanf("%d %d %d", &queries[i].second.first, &queries[i].second.second,
          &queries[i].first);
  }
  sort(queries, queries + q);
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++) a[i][j] = 0;
  for (i = 0; i < q; i++)
    a[queries[i].second.first][queries[i].second.second] = 1;
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      pa[i][j] = pa[i][j - 1] + pa[i - 1][j] - pa[i - 1][j - 1] + a[i][j];
  int broken = 0;
  for (i = 1; i <= n - k + 1; i++)
    for (j = 1; j <= m - k + 1; j++) {
      int sum = pa[i + k - 1][j + k - 1] - pa[i + k - 1][j - 1] -
                pa[i - 1][j + k - 1] + pa[i - 1][j - 1];
      if (sum == k * k) broken = 1;
    }
  if (!broken) {
    cout << -1 << endl;
    return 0;
  }
  int l = 0, r = q - 1;
  while (l < r) {
    for (i = 1; i <= n; i++)
      for (j = 1; j <= m; j++) a[i][j] = 0;
    int mid = (l + r) / 2;
    for (i = 0; i <= mid; i++)
      a[queries[i].second.first][queries[i].second.second] = 1;
    for (i = 1; i <= n; i++)
      for (j = 1; j <= m; j++)
        pa[i][j] = pa[i][j - 1] + pa[i - 1][j] - pa[i - 1][j - 1] + a[i][j];
    int broken = 0;
    for (i = 1; i <= n - k + 1; i++)
      for (j = 1; j <= m - k + 1; j++)
        if (pa[i + k - 1][j + k - 1] - pa[i + k - 1][j - 1] -
                pa[i - 1][j + k - 1] + pa[i - 1][j - 1] ==
            k * k)
          broken = 1;
    if (broken)
      r = mid;
    else
      l = mid + 1;
  }
  cout << queries[l].first << endl;
  return 0;
}
