#include <bits/stdc++.h>
using namespace std;
const int N = 505;
const int oo = INT32_MAX - 50;
int g[N][N], a[N][N], cs[N][N], mx[N][N];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n, m, k, q;
  cin >> n >> m >> k >> q;
  memset(g, -1, sizeof(g));
  while (q--) {
    int i, j, tim;
    cin >> i >> j >> tim;
    g[i][j] = (g[i][j] != -1 ? min(g[i][j], tim) : tim);
    a[i][j] = 1;
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cs[i][j] = a[i][j] + cs[i][j - 1] + cs[i - 1][j] - cs[i - 1][j - 1];
    }
  }
  for (int i = 1; i <= n; i++) {
    multiset<int> st;
    for (int j = 1; j <= m; j++) {
      st.insert(g[i][j]);
      if ((int)st.size() > k) st.erase(st.find(g[i][j - k]));
      mx[i][j] = *(--st.end());
    }
  }
  int ans = oo;
  for (int i = k; i <= n; i++) {
    for (int j = k; j <= m; j++) {
      if (cs[i][j] - cs[i - k][j] - cs[i][j - k] + cs[i - k][j - k] == k * k) {
        int x = 0;
        for (int w = i; w > i - k; w--) {
          x = max(x, mx[w][j]);
        }
        ans = min(ans, x);
      }
    }
  }
  cout << (ans == oo ? -1 : ans);
}
