#include <cstdio>
#include <utility>
#include <queue>
#include <vector>
#include <functional>
#include <cstring>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
typedef pair<int,int> mp;
typedef pair<int,mp> mmp;
#define min(a,b) (((a)>(b))?(b):(a))
#define MAX (100000005)
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int R;

int eans[2][250005];
int emap[2][505][505];
class evh{
public:
	int sx,sy,w,h;
	evh(int* ans,int map[][505]){
		scanf("%d%d%d%d",&w,&h,&sx,&sy);
		sx--;sy--;
		rep(y,h)
			rep(x,w)scanf("%d",&(map[x][y]));
		
		int no=1;
		ans[0]=0;
		priority_queue<mmp,vector<mmp>,greater<mmp> > que;
		que.push( mmp(1,mp(sx,sy)) );
		while(!que.empty()){
			int nl=que.top().first;
			
			while(!que.empty() && que.top().first<=nl){
				int nx=que.top().second.first,
					ny=que.top().second.second;
				que.pop();
				
				if(map[nx][ny]==-1)continue;
				map[nx][ny]=-1;
				ans[no]=nl;
				//printf("kek  %d %d\n",no,ans[no]);
				no++;
				
				rep(i,4){
					int dx=nx+dir[i][0],dy=ny+dir[i][1];
					//printf("pus %d %d\n",dx,dy);
					if(dx<0 || dx>=w || dy<0 || dy>=h || map[dx][dy]==-1)continue;
					que.push( mmp(map[dx][dy],mp(dx,dy)));
				}
			}
		}
	}
};

int main(void){
	while(true){
		scanf("%d",&R);
		if(R==0)break;
		memset(eans,-1,sizeof(eans));
		evh evh1(eans[0],emap[0]);
		evh evh2(eans[1],emap[1]);
		int ans=MAX;
		rep(i,R+1){
			//printf("res  %d %d %d\n",i,eans[0][i],eans[1][i]);
			if(eans[0][R-i]!=-1 && eans[1][i]!=-1){
				ans=min(ans,eans[0][R-i]+eans[1][i]);
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}