
import java.util.*

fun main(args:Array<String>):Unit {
    while (true){
        val r = readLine()!!.trim().toInt()
        if (r == 0) return
        val (w1, h1, x1, y1) = readLine()!!.trim().split(' ').map(String::toInt)
        val office1 = Array(h1){readLine()!!.trim().split(' ').map(String::toInt).toIntArray()}
        val (w2, h2, x2, y2) = readLine()!!.trim().split(' ').map(String::toInt)
        val office2 = Array(h2){readLine()!!.trim().split(' ').map(String::toInt).toIntArray()}
        val office1Level = calRLevel(office1, Point(x1 - 1, y1 - 1))
        val office2Level = calRLevel(office2, Point(x2 - 1, y2 - 1))
        var minRLevel = Int.MAX_VALUE
        val maxSize = minOf(r, w1 * h1)
        val minSize = maxOf(0, r - w2 * h2)
        for (i in minSize .. maxSize){
            if (minRLevel > office1Level[i] + office2Level[r - i])
                minRLevel = office1Level[i] + office2Level[r - i]
        }
        println(minRLevel)
    }
}
data class Point(val x:Int, val y:Int) {
    operator fun plus(that:Point):Point = Point(x + that.x, y + that.y)
}
fun Point.neighbors():Iterable<Point> {
    return listOf(Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1)).map{it + this}
}
fun calRLevel(securityLevels:Array<IntArray>, start:Point):IntArray{
    val height = securityLevels.size
    val width = securityLevels.first().size
    val res = IntArray(height * width + 1){0}
    val queue = PriorityQueue<Pair<Int, Point>>(compareBy(Pair<Int, Point>::first))
    val isSearched = Array(height){BooleanArray(width){false}}
    isSearched[start.y][start.x] = true
    queue.add(Pair(securityLevels[start.y][start.x], start))
    var max = 1
    var idx = 1
    while (queue.isNotEmpty()){
        val top = queue.remove()
        if (max < top.first)
            max = top.first
        res[idx++] = max
        top.second.neighbors().forEach {
            if (it.x in 0 until width && it.y in 0 until height && !isSearched[it.y][it.x]){
                isSearched[it.y][it.x] = true
                queue.add(Pair(securityLevels[it.y][it.x], it))
            }
        }
    }
    return res
}
