n,v,sy,sx,gy,gx = map(int,input().split()) b = [list(map(int,input().split())) for _ in range(n)] v = min(v,1800) INF = 5000 d = [[[INF]*1801 for _ in range(n)] for _ in range(n)] d[sx-1][sy-1][v] = 0 gx -= 1; gy -= 1 from collections import deque q = deque([(0,v,sx-1,sy-1)]) while q: dv,v,x,y = q.popleft() if x==gx and y==gy: print(dv) exit() for nx,ny in [(x+1,y),(x-1,y),(x,y-1),(x,y+1)]: if 0 <= nx < n and 0 <= ny < n: nv = v - b[nx][ny] if nv <= 0: continue if dv+1 < d[nx][ny][nv]: d[nx][ny][nv] = dv+1 q.append((dv+1,nv,nx,ny)) print(-1)