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 = N.times.map{[-1]*N} visited[start[0]][start[1]] = V q = [[0, V] + start] res = -1 while !q.empty? step, hp, x, y = q.shift if [x, y] == last res = step break end [[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 _step = step + 1 if visited[a][b] < _hp visited[a][b] = _hp elem = [_step, _hp, a, b] # q[q.bsearch_index{|v|(v <=> elem) < 0}||q.size, 0] = [elem] q << elem end } end res end p f([SX-1, SY-1], [GX-1, GY-1])