#include <bits/stdc++.h>
int dr[] = {2, 2, -2, -2, 1, -1, 1, -1};
int dc[] = {1, -1, 1, -1, 2, 2, -2, -2};
int dr1[] = {0, 0, 0, 1, 1, 1, -1, -1, -1};
int dc1[] = {-1, 0, 1, -1, 0, 1, -1, 0, 1};
int dr2[] = {0, 0, 1, -1};
int dc2[] = {1, -1, 0, 0};
using namespace std;
long long int a[505][505], a1[505][505];
int main() {
  long long int n, m, k, q, x, y, t, i, j, j1;
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  while (cin >> n >> m >> k >> q) {
    for (long long int i = 1; i < n + 1; i++) {
      for (long long int j = 1; j < m + 1; j++) a[i][j] = 99999999999999999;
    }
    for (long long int i = 1; i < q + 1; i++) {
      cin >> x >> y >> t;
      a[x][y] = t;
    }
    for (i = 1; i <= n; i++) {
      for (j = 1; j + k - 1 <= m; j++) {
        long long int max1 = 0;
        for (j1 = 0; j1 < k; j1++) {
          max1 = max(max1, a[i][j + j1]);
        }
        a1[i][j] = max1;
      }
    }
    long long int ans = 99999999999999999;
    for (i = 1; i + k - 1 <= n; i++) {
      for (j = 1; j + k - 1 <= m; j++) {
        long long int max1 = 0;
        for (j1 = 0; j1 < k; j1++) {
          max1 = max(a1[i + j1][j], max1);
        }
        ans = min(ans, max1);
      }
    }
    if (ans == 99999999999999999) ans = -1;
    cout << ans << endl;
  }
  return 0;
}
