import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static List<String> map = new ArrayList<>();
    public static List<List<Boolean>> vis = new ArrayList<>();
    static int n, m;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别

        n = in.nextInt();
        m = in.nextInt();

        int ox, oy, ex, ey;
        ox = in.nextInt() - 1;
        oy = in.nextInt() - 1;
        ex = in.nextInt() - 1;
        ey = in.nextInt() - 1;

        for (int i = 0; i < n; ++i) {
            String t = in.next();
            map.add(t);
            vis.add(new ArrayList(Collections.nCopies(m, false)));
        }

        System.out.println(bfs(ox, oy, ex, ey));

    }
    static class point {
        public int x, y;

        public point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    static int dx[] = {0, 0, 1, -1};
    static int dy[] = {1, -1, 0, 0};

    public static int bfs(int ox, int oy, int ex, int ey) {
        int res = 0;

        Deque<point> q = new ArrayDeque();
        q.add(new point(ox, oy));
        vis.get(ox).set(oy, true);

        while (!q.isEmpty()) {
            int size = q.size();
            for (int j = 0; j < size; j++) {	//区别于洪水模型,多加了一层for以便记录深度;
                point p = q.pollFirst();

                if (p.x == ex && p.y == ey)return res;

                for (int i = 0; i < 4; ++i) {
                    int tx = p.x + dx[i];
                    int ty = p.y + dy[i];

                    if (tx >= 0 && tx < n && ty >= 0 && ty < m) {
                        if (map.get(tx).charAt(ty) == '.') {
                            if (!vis.get(tx).get(ty)) {
                                vis.get(tx).set(ty, true);
                                q.addLast(new point(tx, ty));
								//res++; //洪水模型会放在这里,但是会导致记录下所有走过的路,死路也记
                            }
                        }
                    }
                }
            }
            res++;//每层加一
        }

        return -1;
    }
}

Java写得略显麻烦,可能是ArrayList的创建和get与cpp的vector不太通导致的,多繁琐一点