while true
	w, h = gets.chomp.split.map(&:to_i)
	break if [w, h] == [0, 0]

	wall_x, wall_y = [], []
	(h - 1).times{
		wall_x << [1] + gets.chomp.split.map(&:to_i) + [1]
		wall_y << gets.chomp.split.map(&:to_i)
	}
	wall_x << [1] + gets.chomp.split.map(&:to_i) + [1]
	wall_y.unshift(Array.new(w, 1))
	wall_y << Array.new(w, 1)

	step = Array.new(h){Array.new(w, 0)}
	list = [[0, 0, 1]]
	until list.empty?
		y, x, count = list.shift
		if step[y][x] == 0 || step[y][x] > count
			step[y][x] = count
			list << [y, x - 1, count + 1] if wall_x[y][x] == 0
			list << [y, x + 1, count + 1] if wall_x[y][x + 1] == 0
			list << [y - 1, x, count + 1] if wall_y[y][x] == 0
			list << [y + 1, x, count + 1] if wall_y[y + 1][x] == 0
		end
	end
	puts step[h - 1][w - 1]
end

