# 计蒜客-二进制矩阵 BFS

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <queue>
#define MAXN 550
using namespace std;
int a[MAXN][MAXN];
int n,m;
struct Node {
int x,y;// 坐标
int step;
};
bool visited[MAXN][MAXN];
int x1,y11,x2,y2;// 这里写y1代码交上去会报编译错误，估计可能是哪个库里面起了个变量名冲突了
queue<Node> q;
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};

void BFS() {
Node node = (Node){x1,y11,0};
visited[x1][y11] = true;
q.push(node);
while(!q.empty()) {
Node top = q.front();
q.pop();
// 检查是否已经到终点
if(top.x == x2 && top.y == y2) {
printf("%d\n",top.step);
exit(0);
}
// 遍历4个方向
int bit = 1;
for(int i = 0;i < 4;i++) {
bit = 1<<i;
int xx = top.x + dir[i][0];
int yy = top.y + dir[i][1];
// 越界
if(xx <= 0 || xx > n || yy <= 0 || yy > m) continue;
if(a[top.x][top.y] & bit) continue;
// 避免回溯
if(visited[xx][yy]) continue;
q.push((Node){xx,yy,top.step+1});
visited[xx][yy] = true;
}
}
}

int main() {
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;i++)
for(int j = 1;j <= m;j++) {
scanf("%d",&a[i][j]);
}
scanf("%d%d%d%d",&x1,&y11,&x2,&y2);
if(x1==x2&&y11==y2) {
printf("0\n");
return 0;
}
BFS();
printf("-1\n");

return 0;
}