#include<bits/stdc++.h>
using namespace std;

int main(){
    int N,K;cin >> N >> K;
    vector<vector<int> >A(N,vector<int>(N));
    for (int i=0;i<N;i++){
        for (int j=0;j<N;j++){
            cin >> A[i][j];
        }
    }
    int r=1000000008;
    int l=-1;
    while (abs(r-l)>1){
        int m=(r+l)/2;
        vector<vector<int> >high_low(N,vector<int>(N,0));
        for (int i=0;i<N;i++){
            for (int j=0;j<N;j++){
                if (A[i][j]<=m) high_low[i][j]=1;
            }
        }
        vector<vector<int> > dp(N,vector<int>(N));
        for (int i=0;i<N;i++){
            for (int j=0;j<N;j++){
                dp[i][j]+=high_low[i][j];
                if (i-1>=0) dp[i][j]+=dp[i-1][j];
                if (j-1>=0) dp[i][j]+=dp[i][j-1];
                if (i-1>=0 && j-1>=0) dp[i][j]-=dp[i-1][j-1];
            }
        }
        int count=0;
        int centers=0;
        for (int i=K-1;i<N;i++){
            for (int j=K-1;j<N;j++){
                count=0;
                count+=dp[i][j];
                if (i-K>=0) count-=dp[i-K][j];
                if (j-K>=0) count-=dp[i][j-K];
                if (i-K>=0 && j-K>=0) count+=dp[i-K][j-K];
                if (K%2==0){
                    if (K*K/2<=count) centers++;
                }else{
                    if (K*K/2+1<=count) centers++;
                }
            }
        }
        if (centers>=1) r=m;
        else l=m;
    }
    cout << r << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
  
#define fst ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int long long
#define tc int tt; cin >> tt; while(tt--) 
#define pb push_back
#define mp make_pair
#define ff first
#define ss second

const int N = 2e5 + 5, mod = 1e9 + 7, INF = 1e16 + 6;	

int power(int a, int n) {
	int res = 1;
	while(n) {
		if(n&1) res = (res*a)%mod;
		n >>= 1;
		a = (a*a)%mod;
	}
	return res;
}

int32_t main()
{
	fst
	#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout); 
	#endif
	
	int n, m;
	cin >> n >> m;
	int mat[n][m];
	int mn = 1e18;
	for(int i=0;i<n;++i) {
		for(int j=0;j<m;++j) cin >> mat[i][j], mn = min(mn, mat[i][j]);
	}
	
	int ans = 0;
	for(int i=0;i<n;++i) {
		for(int j=0;j<m;++j) ans += (mat[i][j] - mn);
	}
cout << ans;
}