#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>	// require sort next_permutation count __gcd reverse etc.
#include <cstdlib>	// require abs exit atof atoi 
#include <cstdio>		// require scanf printf
#include <functional>
#include <numeric>	// require accumulate
#include <cmath>		// require fabs
#include <climits>
#include <limits>
#include <cfloat>
#include <iomanip>	// require setw
#include <sstream>	// require stringstream 
#include <cstring>	// require memset
#include <cctype>		// require tolower, toupper
#include <fstream>	// require freopen
#include <ctime>		// require srand
#define rep(i,n) for(int i=0;i<(n);i++)
#define ALL(A) A.begin(), A.end()
#define INF 3000000
using namespace std;

typedef long long ll;
typedef pair<int, int> P;
int a[55][55];
int b[55][55];
int c[55][55];
int main()
{
	memset (a, 0, sizeof (a ) );
	memset (b, 0, sizeof (b ) );
	memset (c, 0, sizeof (c ) );
	ios_base::sync_with_stdio(0);
	int H, W; cin >> H >> W;
	rep (i, H ) rep (j, W ) cin >> a[i][j];
	rep (i, H ) rep (j, W ) cin >> b[i][j];
	int h, w; cin >> h >> w;
	rep (i, h ) rep (j, w ) cin >> c[i][j];

	int res = -INF;
	bool found = false;
	rep (i, H-h+1 ) rep (j, W-w+1 ){
		bool match = true;
		int cur = 0;
		rep (row, h ){
			rep (col, w ){
			 	if (b[i+row][j+col] != c[row][col] ){
					match = false; 
					break;
				}else{
					cur += a[i+row][j+col];
				} // end if
			} // end rep
			if (!match ) break;
		} // end rep
		if (match ){
			res = max (res, cur );
			found |= true;
		} // end if
	} // end rep
	if (!found ){
		cout << "NA" << endl;
	}else{
		cout << res << endl;
	} // end if
	return 0;
}
