#include <bits/stdc++.h>
using namespace std;
const int N = 1001;
int n, arr[N][N], k, q, m, I, t, J, Left[N][N], down[N][N];
int main() {
  cin >> n >> m >> k >> q;
  memset(arr, -1, sizeof(arr));
  for (int i = 0; i < q; i++) {
    cin >> I >> J >> t;
    arr[I][J] = t;
  }
  memset(down, -1, sizeof(down));
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (i + k - 1 > n) continue;
      int mx = arr[i][j];
      for (int ii = i, id = 0; id < k; id++, ii++) {
        if (arr[ii][j] > mx && mx != -1) {
          mx = arr[ii][j];
        }
        if (arr[ii][j] == -1) {
          mx = -1;
        }
      }
      down[i][j] = mx;
    }
  }
  int mn = 1000000001;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (j + k - 1 > m) continue;
      bool M = 1;
      int mx = -1;
      for (int jj = j, id = 0; id < k; id++, jj++) {
        if (down[i][jj] == -1) M = 0;
        mx = max(mx, down[i][jj]);
      }
      if (M) mn = min(mn, mx);
    }
  }
  if (mn != 1000000001)
    cout << mn << endl;
  else
    cout << -1 << endl;
}
