N, V, SX, SY, GX, GY = gets.split.take(6).map(&:to_i) MAP = N.times.map{ gets.split.take(N).map(&:to_i) } def f(start, last) visited = Hash.new -1 visited[start] = V q = {start=>V} step = 0 while !q.empty? step += 1 qq = {} q.each{|(x, y), hp| [[x+1, y], [x-1, y], [x, y+1], [x, y-1]].each{|a, b| next if !a.between?(0, N-1) next if !b.between?(0, N-1) _hp = hp - MAP[b][a] next if _hp < 1 return step if [a, b] == last if visited[[a,b]] < _hp visited[[a,b]] = _hp qq[[a,b]] = _hp end } } q = qq end -1 end p f([SX-1, SY-1], [GX-1, GY-1])