class PQueue
  Node = Struct.new(:value, :priority)
  def initialize
    @heap = []
  end
  def size; @heap.size; end
  def empty?; @heap.empty?; end
  def peek; empty? ? nil : @heap[0].value; end
  def enq(value, priority)
    el = Node.new(value, priority)
    j = @heap.size
    @heap << nil
    while j > 0
      up = (j - 1) / 2
      break if @heap[up].priority < el.priority
      @heap[j] = @heap[up]
      j = up
    end
    @heap[j] = el
    self
  end
  def deq
    return nil if empty?
    if size == 1
      ret = @heap.shift;
      return [ret.value, ret.priority]
    end
    
    ret = @heap[0]
    @heap[0] = nil
    el = @heap.pop
    
    i = 0
    while 2 * i + 1 < @heap.size
      l = 2 * i + 1
      r = 2 * i + 2
      j = (r == @heap.size || @heap[l].priority <= @heap[r].priority) ? l : r
      break if el.priority <= @heap[j].priority
      @heap[i] = @heap[j]
      i = j
    end
    @heap[i] = el
    return [ret.value, ret.priority]
  end
end

H,W = gets.split.map(&:to_i)
sy,sx = gets.split.map(&:to_i).map{|v| v - 1}
ty,tx = gets.split.map(&:to_i).map{|v| v - 1}
MAP = H.times.map{ gets.chomp }

pq = PQueue.new()
pq.enq(W * sy + sx, 0)
dist = Array.new(H * W, 100_000_000)

until pq.empty?
  u, d = pq.deq
  
  dist[u] = d
  if u == W * ty + tx
    puts d
    exit
  end
  
  y, x = u.divmod(W)

  (y - 2 .. y + 2).each do |y_|
    (x - 2 .. x + 2).each do |x_|
      next if y_ < 0 || y_ >= H || x_ < 0 || x_ >= W
      d_ = (x - x_).abs + (y - y_).abs == 1 ? 0 : 1
      if MAP[y_][x_] == '.' && dist[W * y_ + x_] > d + d_
        pq.enq(W * y_ + x_ , d + d_) 
        dist[W * y_ + x_] = d + d_
      end
    end
  end
end
puts -1

