Problem:
Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2

Solution in C# (.NET Core 3.1.201) (judge verdict: Time Limit Exceeded)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using static System.Math;

namespace CSharpSpiral {
	class Program {
		public static void Main(string[] args) {
			var sw = new StreamWriter(Console.OpenStandardOutput()) {
				AutoFlush =
#if DEBUG
			true
#else
			false
#endif
			};
			Console.SetOut(sw);
			new Program().Solve(new ConsoleInput(
#if DEBUG
			new StreamReader("../../../inputData.txt")
#else
			Console.In
#endif
			, ' '));
			Console.Out.Flush();
		}

		public void Solve(ConsoleInput cin) {
			var H = cin.ReadInt;var W = cin.ReadInt;
			var C = cin.ReadIntArray(2);
			var D = cin.ReadIntArray(2);
			var S = new bool[H, W];
			for(int i = 0; i < H; i++) {
				var line = cin.ReadLine;
				for(int j = 0; j < W; j++) {
					S[i, j] = line[j] == '#';
				}
			}
			var G = new Graph<int>(H*W);
			for(int i = 0; i < H; i++) {
				for(int j = 0; j < W; j++) {
					if(!S[i,j]) {
						if(j<W-1&&!S[i,j+1]) {
							G.AddEdge(i * W + j, i * W + j + 1, 1);
							G.AddEdge(i * W + j + 1, i * W + j, 1);
						}
						if(i<H-1&&!S[i+1,j]) {
							G.AddEdge(i * W + j, (i + 1) * W + j, 1);
							G.AddEdge((i + 1) * W + j, i * W + j, 1);
						}
					}
				}
			}
			var groups = new int[H, W];
			for(int i = 0; i < H; i++) {
				for(int j = 0; j < W; j++) {
					groups[i, j] = -2;
				}
			}
			var count = 0;
			for(int i = 0; i < H; i++) {
				for(int j = 0; j < W; j++) {
					if(S[i, j]) {
						groups[i, j] = -1;
						continue;
					}else{
						if(groups[i,j]<0) {
							G.PointDFS(i * W + j, k => groups[k / W, k % W] = count, null);
							count++;
						}
					}
				}
			}

			var worlds = new GraphX(count);
			var Done = new List<int>[count];
			for(int i = 0; i < count; i++) {
				Done[i] = new List<int>();
			}
			for(int i = 0; i < H; i++) {
				for(int j = 0; j < W; j++) {
					if(S[i, j]) continue;

					var belong = groups[i, j];
					for(int ii = -2; ii <= 2; ii++) {
						if(i + ii < 0 || i + ii >= H) continue;
						for(int jj = -2; jj <= 2; jj++) {
							if(j + jj < 0 || j + jj >= W) continue;
							if(S[i + ii, j + jj]) continue;
							var nextW = groups[i + ii, j + jj];
							if(nextW != belong && !Done[belong].Contains(nextW) && !Done[nextW].Contains(belong)) {
								worlds.AddEdge(nextW, belong, 1);
								worlds.AddEdge(belong, nextW, 1);
								Done[belong].Add(nextW);
								Done[nextW].Add(belong);
							}
						}
					}
				}
			}

			var startW = groups[C[0] - 1, C[1] - 1];
			var M = worlds.Dijkstra(groups[C[0] - 1, C[1] - 1]);
			var goalW = groups[D[0] - 1, D[1] - 1];
			Console.WriteLine(M[goalW] > 11111111L ? -1 : M[goalW]);
		}

	}

	static class ExtendClass {
		public static string Join<T>(this IEnumerable<T> X, string separator = " ")
			=> string.Join(separator, X);
	}
	class ConsoleInput {
		private readonly TextReader _stream;
		private readonly char _separator = ' ';
		private readonly Queue<string> inputStream;
		public ConsoleInput(TextReader stream, char separator = ' ') {
			this._separator = separator;
			this._stream = stream;
			inputStream = new Queue<string>();
		}
		public string Read {
			get {
				if(inputStream.Count != 0) return inputStream.Dequeue();
				string[] tmp = _stream.ReadLine().Split(_separator);
				for(int i = 0; i < tmp.Length; ++i)
					inputStream.Enqueue(tmp[i]);
				return inputStream.Dequeue();
			}
		}
		public string ReadLine { get { return _stream.ReadLine(); } }
		public int ReadInt { get { return int.Parse(Read); } }
		public long ReadLong { get { return long.Parse(Read); } }
		public double ReadDouble { get { return double.Parse(Read); } }
		public string[] ReadStrArray(long N) {
			var ret = new string[N];
			for(long i = 0; i < N; ++i)
				ret[i] = Read;
			return ret;
		}
		public int[] ReadIntArray(long N) { var ret = new int[N]; for(long i = 0; i < N; ++i) ret[i] = ReadInt; return ret; }
		public long[] ReadLongArray(long N) { var ret = new long[N]; for(long i = 0; i < N; ++i) ret[i] = ReadLong; return ret; }
		public double[] ReadDoubleArray(long N) { var ret = new double[N]; for(long i = 0; i < N; ++i) ret[i] = ReadDouble; return ret; }
		public bool isEOF {
			get { return _stream.Peek() == -1; }
		}
	}
	class Edge<V>: IComparable<Edge<V>> where V : IComparable<V> {
		public int In { get; set; }
		public int Out { get; set; }
		public V cost { get; set; }
		public int CompareTo(Edge<V> y) => cost.CompareTo(y.cost);
	}
	class Node<V>: IComparable<Node<V>> where V : IComparable<V> {
		public V Value { get; set; }
		public int index { get; set; }
		public int CompareTo(Node<V> y) => Value.CompareTo(y.Value);
	}
	class PriorityQueue<T> where T : IComparable<T> {
		protected readonly List<T> body = new List<T>();
		protected Comparer<T> comparer { get; }
		public PriorityQueue(bool maxTop = true) {
			comparer
			= maxTop ? Comparer<T>.Create((T i, T j) => i.CompareTo(j))
			: Comparer<T>.Create((T i, T j) => j.CompareTo(i));
		}
		public PriorityQueue(Comparer<T> mComparer) { comparer = mComparer; }
		//suppose Me>Her if isRootMaximum
		protected int Compare(T Me, T Her) => comparer.Compare(Me, Her);
		protected int Compare(int x, int y) => Compare(body[x], body[y]);
		protected virtual void Swap(int x, int y) { T tmp = body[x]; body[x] = body[y]; body[y] = tmp; }
		public virtual void Push(T elem) {
			body.Add(elem);
			//the parent of n-th element is the ((n+1)>>1)-1-th
			UpHeap(lastIndex);
		}
		public void Push(IEnumerable<T> seq) {
			foreach(var item in seq) {
				Push(item);
			}
		}
		protected int UpHeap(int j) {
			while(j > 0) {
				int parent = ((j + 1) >> 1) - 1;
				if(Compare(parent, j) < 0) {
					Swap(parent, j);
				} else break;
				j = parent;
			}
			return j;
		}
		public virtual T Pop() {
			T top = body[0];
			Swap(0, lastIndex);
			body.RemoveAt(lastIndex);
			DownHeap(0);
			return top;
		}
		protected int DownHeap(int j) {
			while(j < length) {
				var leftChild = ((j + 1) << 1) - 1;
				if(leftChild >= length) break;
				var toSwap = leftChild;
				var rightChild = leftChild + 1;
				if(rightChild < length && Compare(leftChild, rightChild) < 0)
					toSwap = rightChild;
				if(Compare(j, toSwap) < 0) {
					Swap(toSwap, j);
				} else break;
				j = toSwap;
			}
			return j;
		}
		public T Top { get { return body[0]; } }
		public int length { get { return body.Count(); } }
		protected int lastIndex { get { return body.Count() - 1; } }
		public bool Any() => body.Any();
		public string Emit() { return body.ToArray().Join(","); }
	}
	class ImmutablePriorityQueue<T>: PriorityQueue<T> where T : IComparable<T> {
		public Dictionary<T, int> map { get; private set; } = new Dictionary<T, int>();
		public ImmutablePriorityQueue(bool maxTop) : base(maxTop) { }
		public ImmutablePriorityQueue(Comparer<T> mComparer) : base(mComparer) { }
		protected override void Swap(int x, int y) {
			map[body[x]] = y;
			map[body[y]] = x;
			base.Swap(x, y);
		}
		public override void Push(T elem) {
			map.Add(elem, length);
			base.Push(elem);
		}
		public override T Pop() {
			var V = base.Pop();
			map.Remove(V);
			return V;
		}
		public void Remove(T X) {
			var x = map[X];
			map.Remove(X);
			Swap(x, lastIndex);
			body.RemoveAt(lastIndex);
			var b = DownHeap(x);
			if(b == x) UpHeap(x);
		}
		public void Update(T X) {
			var x = map[X];
			var b = DownHeap(x);
			if(b == x) UpHeap(x);
		}
		public bool hasKey(T X) { int c; return map.TryGetValue(X, out c); }
	}
	class GraphX: GraphX<long> {
		public GraphX(int count) : base(count) { }
		public long[] Dijkstra(int start) {
			var PQ = new ImmutablePriorityQueue<Node<long>>(false);
			const long large = 0x3FFFFFFFFFFFFFFF;
			var Nodes = new Node<long>[N];
			var picked = new bool[N];
			var parentIndex = Enumerable.Repeat(-1, N).ToArray();
			var O = Outs;
			for(int i = 0; i < N; i++) {
				Nodes[i] = new Node<long> {
					index = i,
					Value = i == start ? 0 : large
				};
				PQ.Push(Nodes[i]);
			}
			while(PQ.Any()) {
				var nv = PQ.Pop();
				var v = nv.index;
				picked[v] = true;
				foreach(var e in O[v]) {
					var w = e.Out;
					if(picked[w]) continue;
					var c = e.cost;
					if(Nodes[v].Value + c < Nodes[w].Value) {
						Nodes[w].Value = Nodes[v].Value + c;
						PQ.Update(Nodes[w]);
						parentIndex[w] = v;
					}
				}
			}
			return Nodes.Select(n => n.Value).ToArray();
		}
		public long Prim(out GraphX tree, int start = 0) {
			tree = new GraphX(N);
			var res = 0L;
			var PQ = new PriorityQueue<Edge<long>>(false);
			var O = Outs;
			PQ.Push(O[start]);
			var picked = new bool[N];
			picked[start] = true;
			while(PQ.Any()) {
				var e = PQ.Pop();
				var w = e.Out;
				if(picked[w]) continue;
				else picked[w] = true;
				res += e.cost;
				tree.Edges.Add(e);
				PQ.Push(O[w]);
			}
			return res;
		}
	}

	class Graph<T> {
		public readonly int N;
		public T[] Nodes { get; }
		protected List<int>[] Nexts { get; }
		protected Dictionary<int, T>[] Edges { get; set; }
		public Graph(int _N) {
			N = _N;
			Nodes = new T[_N];
			Nexts = new List<int>[_N];
			Edges = new Dictionary<int, T>[_N];
			for(int i = 0; i < _N; i++) {
				Nexts[i] = new List<int>();
				Edges[i] = new Dictionary<int, T>();
			}
		}
		public void Update(int i, T value) {
			Nodes[i] = value;
		}
		public void AddEdge(int from, int to, T value) {
			Edges[from].Add(to, value);
			Nexts[from].Add(to);
		}
		public void PointDFS(int from, Action<int> onEnter, Action<int> onLeave) {
			var S = new Stack<int>();
			S.Push(from);
			var entered = new bool[N];
			var departed = new bool[N];//dep<=ent
			var childCount = new int[N];
			while(S.Any()) {
				var v = S.Peek();
				if(!entered[v]) {
					onEnter?.Invoke(v);
					entered[v] = true;
				}
				for(int i = childCount[v]; i < Nexts[v].Count; i++) {
					if(!entered[Nexts[v][i]]) {
						S.Push(Nexts[v][i]);
						childCount[v] = i + 1;
						goto NextLoop;
					}
				}
				S.Pop();
				childCount[v] = Nexts[v].Count;
				if(!departed[v]) {
					onLeave?.Invoke(v);
					departed[v] = true;
				}
			NextLoop:;
			}
		}
		public void MaxMatching() {
			var matching = new List<Tuple<int, int>>();
		}
	}
	class GraphX<V> where V : IComparable<V> {
		public int N { get; }
		public GraphX(int count) {
			N = count;
			Edges = new List<Edge<V>>();
		}
		public List<Edge<V>> Edges { get; }
		public void AddEdge(int In, int Out, V Value) {
			var e = new Edge<V> { In = In, Out = Out, cost = Value };
			Edges.Add(e);
		}
		protected List<Edge<V>>[] Outs {
			get {
				var Res = new List<Edge<V>>[N];
				for(int i = 0; i < N; i++)
					Res[i] = new List<Edge<V>>();
				foreach(var e in Edges)
					Res[e.In].Add(e);
				return Res;
			}
		}
		protected List<Edge<V>>[] Ins {
			get {
				var Res = new List<Edge<V>>[N];
				for(int i = 0; i < N; i++)
					Res[i] = new List<Edge<V>>();
				foreach(var e in Edges)
					Res[e.Out].Add(e);
				return Res;
			}
		}
		public bool DepthFirstSearch(int start, Action<int> OnEnter, Action<int> OnLeave)
			=> DepthFirstSearch(start, i => { OnEnter?.Invoke(i); return false; }, i => { OnLeave?.Invoke(i); return false; });
		public bool DepthFirstSearch(int start, Func<int, bool> OnEnter, Func<int, bool> OnLeave) {
			var Next = Outs;
			var visited = new bool[N];
			visited[start] = true;
			var S = new Stack<int>();
			S.Push(start);
			while(S.Any()) {
				var v = S.Peek();
				if(OnEnter?.Invoke(v) ?? false)
					return true;
				var E = Next[v].FirstOrDefault(e => !visited[e.Out]);
				if(E != default(Edge<V>)) {
					var o = E.Out;
					S.Push(o);
					visited[o] = true;
				} else {
					S.Pop();
					if(OnLeave?.Invoke(v) ?? false)
						return true;
				}
			}
			return false;
		}
		public void BreadthFirstSearch(int start, Action<int> F) {
			var Q = new Queue<int>();
			var Labeled = new bool[N];
			var G = Outs;
			Q.Enqueue(start);
			Labeled[start] = true;
			F(start);
			while(Q.Any()) {
				var v = Q.Dequeue();
				F(v);
				foreach(var e in G[v]) {
					var w = e.Out;
					if(Labeled[w]) continue;
					Q.Enqueue(w);
					Labeled[w] = true;
				}
			}
		}
		public bool hasPath(int from, int to) {
			if(from == to) return true;
			return DepthFirstSearch(from, i => i == to, null);
		}
		public bool MakePath(int from, int to, Stack<int> Path) {
			if(from == to) return true;
			Path = new Stack<int>();
			return DepthFirstSearch(from,
			i => { Path.Push(i); return i == to; },
			j => { Path.Pop(); return false; });
		}
		public bool hasCircuit(int start) {
			var X = PreLabel(start);
			Func<int, int, bool> isBackward = (i, j) => X[i] != -1 && X[j] != -1 && X[i] > X[j];
			return Edges.Any(e => isBackward(e.In, e.Out));
		}
		public List<int> PreOrder(int start) {
			var Res = new List<int>();
			DepthFirstSearch(start, v => Res.Add(v), null);
			return Res;
		}
		public List<int> PostOrder(int start) {
			var Res = new List<int>();
			DepthFirstSearch(start, null, v => Res.Add(v));
			return Res;
		}
		public int[] PreLabel(int start) {
			var Res = Enumerable.Repeat(-1, N).ToArray();
			var count = 0;
			DepthFirstSearch(start, v => Res[v] = count++, null);
			return Res;
		}
		public int[] PostLabel(int start) {
			var Res = Enumerable.Repeat(-1, N).ToArray();
			var count = 0;
			DepthFirstSearch(start, null, v => Res[v] = count++);
			return Res;
		}
	}
}