class UnionFind
	def initialize
		@obj_to_node = {}
	end

	def add(obj)
		@obj_to_node[obj] ||= Node.new(obj)
	end

	def size(x = nil)
		x ? @obj_to_node[x].root.size : @obj_to_node.size
	end

	class Node
		def initialize(obj)
			@obj = obj
			@parent = self
			@size = 1
			@rank = 0
		end

		def root
			return self if @parent == self
			@parent = @parent.root
		end	

		attr_accessor :parent, :size, :rank
	end

	def union(x, y)
		u = (@obj_to_node[x] ||= Node.new(x)).root
		v = (@obj_to_node[y] ||= Node.new(y)).root
		return if u == v
		if u.rank > v.rank
			v.parent = u
			u.size += v.size
		elsif v.rank > u.rank
			u.parent = v
			v.size += u.size
		else
			u.parent = v
			v.rank += 1
			v.size += u.size
		end
	end

	def same?(x, y)
		return false unless u = @obj_to_node[x]
		return false unless v = @obj_to_node[y]
		u.root == v.root
	end
end


loop {
	r = gets.to_i
	break if r == 0

	room_auth = []
	2.times {
		w, h, x, y = gets.split.map &:to_i
		a = (1..h).map{gets.split.map &:to_i}
		edges = {}
		(0..h-1).each{|i|
			(0..w-1).each{|j|
				if i < h-1
					p1, p2 = a[i][j], a[i+1][j]
					p3 = (p1 > p2 ? p1 : p2)
					(edges[p3] ||= []) << [i*w+j, (i+1)*w+j]
				end
				if j < w-1
					p1, p2 = a[i][j], a[i][j+1]
					p3 = (p1 > p2 ? p1 : p2)
					(edges[p3] ||= []) << [i*w+j, i*w+j+1]
				end
			}
		}

		edges = edges.to_a.sort_by(&:first)
		uf = UnionFind.new
		uf.add((y-1)*w+x-1)
		hash = {0 => 0, 1 => 1}
	
		until edges.empty?
			auth, auth_edges = edges.shift
			auth_edges.each{|e|
				uf.union(e[0], e[1])
			}
			hash[auth] = uf.size((y-1)*w+x-1)
		end
		room_auth << hash.invert.to_a
	}

	min = Float::INFINITY

	j = room_auth[1].size-1
	(0..room_auth[0].size-1).each{|i|
		room1, auth1 = room_auth[0][i]
		j -= 1 until j == 0 || room1 + room_auth[1][j-1][0] < r
		room2, auth2 = room_auth[1][j]
		min = auth1 + auth2 if auth1 + auth2 < min
	}
	p min
}