$vwall = Array.new(30)
$hwall = Array.new(30)
$dx = [0,1,0,-1]
$dy = [1,0,-1,0]
def bfs(sy, sx, steps, q, h, w)
    for i in 0..3
        cy = sy + $dy[i]
        cx = sx + $dx[i]
        if cy.between?(0,h-1) && cx.between?(0,w-1) && steps[cy][cx] ==1000
            if i == 0
                next if sy == h-1 || $hwall[sy][sx] == 1
            elsif i == 1
                next if sx == w-1 || $vwall[sy][sx] == 1
            elsif i == 2
                next if sy == 0 || $hwall[sy-1][sx] == 1
            else
                next if sx == 0 || $vwall[sy][sx-1] == 1
            end
            q.push([cy,cx])
            steps[cy][cx] = steps[sy][sx] + 1
        end
    end
    while q.size > 0
        cy, cx = q.shift
        steps = bfs(cy,cx,steps,q,h,w)
    end
    return steps
end

while line = gets
    w, h = line.split.map(&:to_i)
    break if w == 0 && h == 0
    steps = Array.new(h).map{Array.new(w,1000)}
    steps[0][0] = 1
    h.times do |i|
        $vwall[i] = gets.split.map(&:to_i)
        break if i == h-1
        $hwall[i] = gets.split.map(&:to_i)
    end
    bfs(0, 0, steps, [], h, w)
    puts steps[h-1][w-1] == 1000 ? 0 : steps[h-1][w-1]
end