class Point attr_reader :x, :y def initialize(x, y) @x = x @y = y end def in?(n) 0 < @x && @x <= n && 0 < @y && @y <= n end def left Point.new(@x + 1, @y) end def right Point.new(@x - 1, @y) end def up Point.new(@x, @y + 1) end def down Point.new(@x, @y - 1) end def eql?(other) @x == other.x && @y == other.y end def ==(other) eql?(other) end def hash @x + @y * 100 end end n, v, sx, sy, gx, gy = gets.split.map(&:to_i) map = Hash.new(0) vmap = Hash.new(-1) (1..n).each do |y| gets.split.map(&:to_i).each.with_index(1) do |l, x| map[Point.new(x, y)] = l end end s = Point.new(sx, sy) g = Point.new(gx, gy) count = 0 list = {} list[s] = v vmap[s] = v loop do count += 1 next_list = {} list.each do |point, life| [point.left, point.right, point.up, point.down].each do |next_point| if next_point.in?(n) next_life = life - map[next_point] if next_life > 0 if next_point == g puts count exit elsif next_life > vmap[next_point] vmap[next_point] = next_life next_list[next_point] = next_life end end end end end if next_list.empty? break end list = next_list end puts(-1)