#include<iostream>
#include<cmath>
#include<vector>
#include<bitset>
#include<bitset>
#include<string>
#include<utility>
#include<queue>
#include <iomanip>
#include <limits>
#include<tuple>
#include<algorithm>
#include<set>

using namespace std;
typedef long long int ll;
// ll 
int main(){
    int n,k;
    cin >> n >> k;
    vector<vector<ll>> a(n+1,vector<ll>(n+1));
    ll ok=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin >> a.at(i+1).at(j+1);
            ok=max(a.at(i+1).at(j+1),ok);
        }
    }
    ll ng=(-1);
    ll mid;
    // cout << ok << endl;
    bool ind=false;
    while(ok>ng+1){
        
        mid=(ok+ng)/2;
        // cout << ng <<"," << ok << "," << mid << endl;
        vector<vector<ll>> s(n+1,vector<ll>(n+1,0));
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                s.at(i).at(j)=s.at(i-1).at(j)+s.at(i).at(j-1)-s.at(i-1).at(j-1);
                if(mid<a.at(i).at(j))s.at(i).at(j)++;
            }
        }
        ind=false;
        for(int i=k;i<=n;i++){
            for(int j=k;j<=n;j++){
                if(s.at(i).at(j)-s.at(i-k).at(j)-s.at(i).at(j-k)+s.at(i-k).at(j-k)<k*k/2+1){
                    ind=true;
                    break;
                }
            }
            if(ind)break;
        }
        if(ind){
            ok=mid;
        }else{
            ng=mid;
        }
    }
    cout << ok << endl;
    return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<sstream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<climits>
#include<cmath>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<numeric>
#include<functional>
#include<algorithm>
#include<bitset>
#include<tuple>
#include<unordered_set>
#include<unordered_map>
#include<random>
#include<array>
#include<cassert>
using namespace std;
#define INF ((1<<30)-1)
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define all(v) v.begin(),v.end()


int dp[1001][1001];

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int n, m;
	int a[1000], b[1000];
	cin >> n >> m;
	rep(i, n)cin >> a[i];
	rep(i, m)cin >> b[i];

	rep(i, n + 1)rep(j, m + 1)dp[i][j] = INF;
	dp[0][0] = 0;
	rep(i, n + 1)rep(j, m + 1) {
		int d = dp[i][j];
		if (i < n)dp[i + 1][j] = min(dp[i + 1][j], d + 1);
		if (j < m)dp[i][j + 1] = min(dp[i][j + 1], d + 1);
		if (i < n && j < m) {
			dp[i + 1][j + 1] = min(dp[i + 1][j + 1], d + (a[i] != b[j]));
		}
	}


	cout << dp[n][m] << endl;




	return 0;
}
