#include <bits/stdc++.h>
using namespace std;
int C[543][543];
int dp[543][501];
int main() {
  int n, m, k, q, x, y, t;
  scanf("%d %d %d %d", &n, &m, &k, &q);
  for (int i = 0; i < q; i++) {
    scanf("%d %d %d", &x, &y, &t);
    C[x - 1][y - 1] = 1 + t;
  }
  for (int i = 0; i < m; i++) {
    dp[i][1] = C[0][i];
  }
  int Min = 2e9 + 10;
  for (int i = 0; i < n; i++) {
    for (int j = m - 1; j > -1; j--) {
      if (C[i][j] > 0) {
        int w = 0, h = 0;
        for (int l = 1; l <= k; l++) {
          if (j - (l - 1) < 0 || i - (l - 1) < 0) break;
          int a = C[i][j - (l - 1)], b = C[i - (l - 1)][j], c = 0;
          if (j > 0) c = dp[j - 1][l - 1];
          if (a > 0 && b > 0 && (c > 0 || l == 1)) {
            w = max(w, a), h = max(h, b);
            int v = max(w, h);
            dp[j][l] = max(v, c);
          } else
            break;
        }
        if (dp[j][k] > 0 && dp[j][k] < Min) Min = dp[j][k];
      }
    }
  }
  if (Min == 2e9 + 10)
    cout << -1;
  else
    cout << Min - 1;
}
