#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <sstream>
#include <cstring>
#include <cstdlib>

using namespace std;

#define ALL(c) c.begin(),c.end()
#define RALL(c) c.rbegin(),c.rend()
#define REP(i,x,y) for(int i=(x);i<(y);++i)
#define MP(a,b) make_pair((a),(b))
#define F_ first
#define S_ second

typedef long long int lli;
typedef pair<int,int> Pi;
typedef pair<int,Pi> PP;

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

inline bool IsIn(int y,int x,int h,int w){
	return 0<=y&&y<h&&0<=x&&x<w;
}

inline int f(int x){
	if(x==0) return 1;
	else if(x==1) return 0;
}

void Djikstra(vector<vector<int> > &f,vector<vector<int> > &l,int sy,int sx,int h,int w){
	priority_queue<PP,vector<PP>,greater<PP> > que;
	REP(y,0,h) fill(l[y].begin(),l[y].end(),INF);
	l[sy][sx]=1;
	que.push(PP(1,Pi(sy,sx)));
	while(!que.empty()){
		PP p=que.top(); que.pop();
		Pi v=p.S_;
		if(l[v.F_][v.S_]<p.F_) continue;
		REP(i,0,4){
			int ny=v.F_+dy[i],nx=v.S_+dx[i];
			if(!IsIn(ny,nx,h,w)) continue;
			if(l[ny][nx]>max(f[ny][nx],l[v.F_][v.S_])){
				l[ny][nx]=max(f[ny][nx],l[v.F_][v.S_]);
				que.push(PP(l[ny][nx],Pi(ny,nx)));
			}
		}
	}
}

void solve(){
	int R;
	while(cin >> R&&R){
		int W[2],H[2],X[2],Y[2];
		vector<vector<int> > field[2];
		vector<vector<int> > level[2];
		REP(i,0,2){
			cin >> W[i] >> H[i] >> X[i] >> Y[i];
			--X[i]; --Y[i];
			field[i].resize(H[i]);
			level[i].resize(H[i]);
			REP(j,0,H[i]){
				field[i][j].resize(W[i]);
				level[i][j].resize(W[i]);
			}
			REP(y,0,H[i]) REP(x,0,W[i]) cin >> field[i][y][x];
			Djikstra(field[i],level[i],Y[i],X[i],H[i],W[i]);
		}
		map<int,int> s[2];
		vector<int> idx[2],num[2];
		REP(i,0,2){
			REP(y,0,H[i]) REP(x,0,W[i]) ++s[i][level[i][y][x]];
			auto it=s[i].begin();
			idx[i].push_back(0);
			num[i].push_back(0);
			idx[i].push_back(it->F_);
			num[i].push_back(it->S_);
			auto prev=it;
			++it;
			for(; it!=s[i].end(); ++it,++prev){
				it->S_+=prev->S_;
				idx[i].push_back(it->F_);
				num[i].push_back(it->S_);
			}
		}
		int result=INF;
		REP(i,0,2) REP(j,0,idx[i].size()){
			int tmp=(int)(lower_bound(num[f(i)].begin(),num[f(i)].end(),R-num[i][j])-num[f(i)].begin());
			if(!(0<=tmp&&tmp<=idx[f(i)].size()-1)) continue;
			result=min(result,idx[i][j]+idx[f(i)][tmp]);
		}
		cout << result << endl;
	}
}

int main(){
	solve();
	return 0;
}