#include <cstdio>
#include <algorithm>
#include <utility>
#include <vector>
#include <queue>
#include <functional>
using namespace std;

typedef pair<int,int> pii;

const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
const int INF = 1000000000;

vector<pii> gettable(){
	int w, h, x, y;
	scanf("%d%d%d%d", &w, &h, &x, &y);

	vector<int> Ls(1, 0);
	vector<vector<int> > L(h + 2, vector<int>(w + 2, -1));
	for(int i = 1; i <= h; ++i)
	for(int j = 1; j <= w; ++j){
		scanf("%d", &L[i][j]);
		Ls.push_back(L[i][j]);
	}
	Ls.push_back(INF);
	sort(Ls.begin(), Ls.end());
	Ls.erase(unique(Ls.begin(), Ls.end()), Ls.end());
	for(int i = 1; i <= h; ++i)
	for(int j = 1; j <= w; ++j){
		L[i][j] = lower_bound(Ls.begin(), Ls.end(), L[i][j]) - Ls.begin();
	}

	vector<pii> res(Ls.size());
	for(int i = 0; i < Ls.size(); ++i){
		res[i].second = Ls[i];
	}

	priority_queue<pii,vector<pii>,greater<pii> > pq;
	pq.push(pii(L[y][x], y << 16 | x));
	++res[L[y][x]].first;
	L[y][x] = -1;
	while(!pq.empty()){
		int a = pq.top().first;
		y = pq.top().second >> 16 & 0xffff;
		x = pq.top().second & 0xffff;
		pq.pop();

		for(int i = 0; i < 4; ++i){
			int ny = y + dy[i], nx = x + dx[i];
			if(L[ny][nx] >= 0){
				int b = max(a, L[ny][nx]);
				++res[b].first;
				pq.push(pii(b, ny << 16 | nx));
				L[ny][nx] = -1;
			}
		}
	}

	for(int i = 1; i < res.size(); ++i){
		res[i].first += res[i - 1].first;
	}

	return res;
}

int main(){
	int r;
	while(scanf("%d", &r), r){
		vector<pii> v = gettable(), w = gettable();
		int ans = INF;
		for(int i = 0; i < v.size(); ++i){
			pii tmp(r - v[i].first, -INF);
			int k = lower_bound(w.begin(), w.end(), tmp)->second;
			ans = min(ans, v[i].second + k);
		}
		printf("%d\n", ans);
	}
}