#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using vec = vector<ll>;
using mat = vector<vec>;
using pll = pair<ll,ll>;

#define INF (1LL << 60)
#define MOD 1000000007
#define PI 3.14159265358979323846

#define REP(i,m,n) for(ll (i)=(m),(i_len)=(n);(i)<(i_len);++(i))
#define FORR(i,v) for(auto (i):v)
#define ALL(x) (x).begin(), (x).end()
#define PR(x) cout << (x) << endl
#define PS(x) cout << (x) << " "
#define SZ(x) ((ll)(x).size())
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define REV(x) reverse(ALL((x)))
#define ASC(x) sort(ALL((x)))
#define DESC(x) ASC((x)); REV((x))
#define pb push_back
#define eb emplace_back

bool check(mat A, ll X, ll N, ll K)
{
    mat S(N+1, vec(N+1, 0));
    bool f = false;
    REP(i,1,N+1) {
        REP(j,1,N+1) {
            S[i][j] = S[i-1][j] + S[i][j-1] - S[i-1][j-1] + (A[i-1][j-1] > X);
        }
    }
    REP(i,1,N-K+2) {
        REP(j,1,N-K+2) {
            ll cnt = S[i+K-1][j+K-1] - S[i+K-1][j-1] - S[i-1][j+K-1] + S[i-1][j-1];
            if(cnt < K*K/2+1) {
                f = true;
                break;
            }
        }
    }
    return f;
}

int main()
{
    ll N, K;
    cin >> N >> K;
    mat A(N, vec(N));
    REP(i,0,N) {
        REP(j,0,N) cin >> A[i][j];
    }

    ll ng = -1, ok = INF;
    while(abs(ok - ng) > 1) {
        ll mid = (ok + ng) / 2;
        if(check(A, mid, N, K)) ok = mid;
        else ng = mid;
    }
    PR(ok);

    return 0;
}

/*



*/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 5000 + 10;
const LL MOD = 998244353;
int n, m;
LL mpow(LL a, LL x) {
	if (x == 0) return 1;
	LL t = mpow(a, x>>1);
	if (x % 2 == 0) return t * t % MOD;
	return t * t % MOD * a % MOD;
}

LL f[N][N], pw[N][N];

int main() {
	pw[0][0] = 1;
	for (int i = 1; i < N; i ++) {
		pw[i][0] = 1;
		for (int j = 1; j < N; j ++) pw[i][j] = pw[i][j-1] * i % MOD;
	}
	cin >> n >> m;
	for (int i = 1; i <= m; i ++) {
		f[1][i] = pw[m][n-1];
	}
	for (int i = 2; i <= n; i ++) {
		for (int x = 1; x <= m; x ++) {
			f[i][x] = f[i-1][x] - pw[m-x][i-2] * pw[m][n-(i-1)] % MOD + 
				pw[m-x][i-1] * pw[m][n-i] % MOD + 
				pw[m-x][i-2] * (x-1) % MOD * pw[m][n-i] % MOD;
			
			f[i][x] = (f[i][x] % MOD + MOD) % MOD;
			//printf("# %d %d : %d\n", i, x, f[i][x]);
		}
	}
	LL ans = 0;
	for (int i = 1; i <= n; i ++) for (int x = 1; x <= m; x ++) (ans += f[i][x]) %= MOD;
	cout << ans << endl;
}