local mfl = math.floor local n, v, sx, sy, gx, gy = io.read("*n", "*n", "*n", "*n", "*n", "*n") local goalidx = (gy - 1) * n + gx local map = {} for i = 1, n * n do map[i] = io.read("*n") end local life = {} for i = 1, n * n do life[i] = 0 end local n2 = n * n life[(sy - 1) * n + sx] = v local alltasks = {} alltasks[1] = {(sy - 1) * n + sx} local curtaskidx = 1 local function walk(curidx, dstidx) if life[dstidx] < life[curidx] - map[dstidx] then if goalidx == dstidx then print(curtaskidx) return true end table.insert(alltasks[curtaskidx + 1], dstidx) life[dstidx] = life[curidx] - map[dstidx] end return false end local found = false while 0 < #alltasks[curtaskidx] do alltasks[curtaskidx + 1] = {} for i = 1, #alltasks[curtaskidx] do local idx = alltasks[curtaskidx][i] local ret = false if idx % n ~= 0 then found = walk(idx, idx + 1) if found then break end end if idx % n ~= 1 then found = walk(idx, idx - 1) if found then break end end if n < idx then found = walk(idx, idx - n) if found then break end end if idx <= n * n - n then found = walk(idx, idx + n) if found then break end end end if found then break end curtaskidx = curtaskidx + 1 end if not found then print(-1) end