import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); int h = sc.nextInt(); int w = sc.nextInt(); int sr = sc.nextInt() - 1; int sx = sc.nextInt() - 1; int gr = sc.nextInt() - 1; int gc = sc.nextInt() - 1; char[][] field = new char[h][]; for (int i = 0; i < h; i++) { field[i] = sc.next().toCharArray(); } int[][][] costs = new int[h][w][6]; for (int[][] arr : costs) { for (int[] arr1 : arr) { Arrays.fill(arr1, Integer.MAX_VALUE); } } PriorityQueue queue = new PriorityQueue<>(); queue.add(new Path(sr, sx, 0, 0)); while (queue.size() > 0) { Path p = queue.poll(); if (field[p.r][p.c] == '#') { continue; } if (costs[p.r][p.c][p.idx] <= p.value) { continue; } costs[p.r][p.c][p.idx] = p.value; if (p.r > 0) { int nextIdx = p.idx; if (p.idx <= 2) { nextIdx++; } else if(p.idx == 3) { nextIdx = 0; } queue.add(new Path(p.r - 1, p.c, p.value + 1, nextIdx)); } if (p.r < h - 1) { int nextIdx = p.idx; if (p.idx == 0) { nextIdx = 3; } else if (p.idx <= 3) { nextIdx--; } queue.add(new Path(p.r + 1, p.c, p.value + 1, nextIdx)); } if (p.c > 0) { int nextIdx; if (p.idx == 0) { nextIdx = 4; } else if (p.idx == 4) { nextIdx = 2; } else if (p.idx == 2) { nextIdx = 5; } else if (p.idx == 5) { nextIdx = 0; } else { nextIdx = p.idx; } queue.add(new Path(p.r, p.c - 1, p.value + 1, nextIdx)); } if (p.c < w - 1) { int nextIdx; if (p.idx == 0) { nextIdx = 5; } else if (p.idx == 5) { nextIdx = 2; } else if (p.idx == 2) { nextIdx = 4; } else if (p.idx == 4) { nextIdx = 0; } else { nextIdx = p.idx; } queue.add(new Path(p.r, p.c + 1, p.value + 1, nextIdx)); } } if (costs[gr][gc][0] == Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(costs[gr][gc][0]); } } static class Path implements Comparable { int r; int c; int value; int idx; public Path(int r, int c, int value, int idx) { this.r = r; this.c = c; this.value = value; this.idx = idx; } public int compareTo(Path another) { return value - another.value; } } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public Scanner() throws Exception { } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public String next() throws Exception { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }