#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define rrep(i,n) for(int i=1;i<=n;i++)
#define drep(i,n) for(int i=n;i>=0;i--)
#define MAX 160000
#define B 100
#define dpb push_back
#define fi first
#define se second
typedef pair<int, int> P;
typedef long long ll;
const int inf = 1e9;
const ll INF = 1e18;
const int size = 504;
//__gcd(a,b), __builtin_popcount(a);

int r, h1, w1, X1, Y1, h2, w2, X2, Y2;
int dy[4] = {0, 0, -1, 1}, dx[4] = {-1, 1, 0, 0};
int a[size][size], b[size][size];
int an[250010], bn[250010];

int to_n(int y, int x, int w){
	return (w*(y-1)+x);
}
int to_y(int n, int w){
	return ((n-1)/w+1);
}
int to_x(int n, int w){
	return (n-(to_y(n, w)-1)*w);
}
int main(){
	while(1){
	fill((int*)a, (int*)(a+size), inf);
	fill((int*)b, (int*)(b+size), inf);
	fill(an, an+250010, 0);
	fill(bn, bn+250010, 0);
	scanf("%d", &r);
	if(!r)break;
	scanf("%d%d%d%d", &w1, &h1, &X1, &Y1);
	rrep(i,h1)rrep(j,w1)scanf("%d", &a[i][j]);
	scanf("%d%d%d%d", &w2, &h2, &X2, &Y2);
	rrep(i,h2)rrep(j,w2)scanf("%d", &b[i][j]);
	
	priority_queue<P, vector<P>, greater<P> > q;
	q.push(P(a[Y1][X1], to_n(Y1, X1,w1)));
	a[Y1][X1] = inf;
	int acnt = 1;
	while(!q.empty()){
		P p = q.top();q.pop();
		int y = to_y(p.se, w1), x = to_x(p.se, w1);
		an[acnt++] = p.fi;
		for(int i = 0;i < 4;i++){
			int yy = y+dy[i], xx = x+dx[i];
			if(a[yy][xx] != inf){
				q.push(P(a[yy][xx], to_n(yy, xx,w1)));
				a[yy][xx] = inf;
			}
		}
	}
	
	q.push(P(b[Y2][X2], to_n(Y2, X2,w2)));
	b[Y2][X2] = inf;
	int bcnt = 1;
	while(!q.empty()){
		P p = q.top();q.pop();
		int y = to_y(p.se, w2), x = to_x(p.se, w2);
		bn[bcnt++] = p.fi;
		for(int i = 0;i < 4;i++){
			int yy = y+dy[i], xx = x+dx[i];
			if(b[yy][xx] != inf){
				q.push(P(b[yy][xx], to_n(yy, xx,w2)));
				b[yy][xx] = inf;
			}
		}
	}
	
	int t1 = 0, t2 = 0;
	for(int i = 0;i < acnt;i++){
		t1 = max(t1, an[i]);
		an[i] = t1;
	}
	for(int i = 0;i < bcnt;i++){
		t2 = max(t2, bn[i]);
		bn[i] = t2;
	}
	
	int ans = inf;
	for(int i = 0;i < acnt;i++){
		if(r-i < bcnt)ans = min(ans, an[i]+bn[r-i]);
		if(r == i)break;
	}
	
	printf("%d\n", ans);
	}
	return 0;
}




