import java.util.*; public class Main{ static char[][] map = null; static int startX; static int startY; static int endX; static int endY; static int length; static int height; static int width; public static void main(String[] args) { Scanner input = new Scanner(System.in); height = input.nextInt(); width = input.nextInt(); map = new char[height + 2][width + 2]; //为防止边界影响判断,加一圈边界障碍 Arrays.fill(map[0], '*'); Arrays.fill(map[height + 1], '*'); for (int i = 1; i < height + 1; i++) { map[i][0] = '*'; map[i][width + 1] = '*'; } startX = input.nextInt(); startY = input.nextInt(); endX = input.nextInt(); endY = input.nextInt(); String line = input.nextLine(); for (int i = 0; i < height; i++) { line = input.nextLine(); for (int j = 0; j < width; j++) { map[i + 1][j + 1] = line.charAt(j); } } BFS(); System.out.println(length); } public static void BFS() { ArrayList<MyPoint> vers = new ArrayList<>(); ArrayList<MyPoint> newVers = new ArrayList<>(); vers.add(new MyPoint(startX, startY)); int x; int y; while (true) { for (int i = 0; i < vers.size(); i++) { x = vers.get(i).x; y = vers.get(i).y; //System.out.printf("点(%d,%d)找路\n", x, y); if (addVer(x + 1, y, newVers)) return; if (addVer(x - 1, y, newVers)) return; if (addVer(x, y + 1, newVers)) return; if (addVer(x, y - 1, newVers)) return; } if (newVers.size() == 0) { length = -1; return; } vers.clear(); vers.addAll(newVers); newVers.clear(); length++; } } public static boolean addVer(int x, int y, ArrayList<MyPoint> newVers) { if (map[x][y] == '.') { if (!isArrived(x, y)) { //System.out.printf("\t点(%d,%d)可以走\n", x, y); map[x][y] = '-'; newVers.add(new MyPoint(x, y)); } else { length++; return true; } } return false; } public static boolean isArrived(int x, int y) { return (x == endX) && (y == endY); } } class MyPoint { int x; int y; public MyPoint(int x, int y) { this.x = x; this.y = y; } }