# AtCoder Beginner Contest 176
# D - Wizard in Maze
# https://atcoder.jp/contests/abc176/tasks/abc176_d
(H, W) = gets.chomp.split.map(&:to_i)
(Ch, Cw) = gets.chomp.split.map(&:to_i)
(Dh, Dw) = gets.chomp.split.map(&:to_i)

S = readlines.map{|l| l.chomp.split('') }

@start = [Ch-1, Cw-1]
@goal  = [Dh-1, Dw-1]

def movable?(i, j)
  i >= 0 && j >= 0 && i < H && j < W && S[i][j] == '.'
end

INF = 10**10
@magic_count = Array.new(H) { Array.new(W) { INF } }
@magic_count[Ch-1][Cw-1] = 0

def search(si, sj)
  que = [[si, sj]]

  while que.length > 0

    #pp que
    (pi, pj) = que.shift

    # 次の移動先
    [[pi+1, pj], [pi, pj+1], [pi-1, pj], [pi, pj-1]].each do |np|

      (npi, npj) = np

      if np == @goal
        @magic_count[npi][npj] = @magic_count[pi][pj]
        return
      end

      if movable?(npi, npj) && @magic_count[npi][npj] == INF
        que << np
        @magic_count[npi][npj] = @magic_count[pi][pj]
      end
    end
  end
end

def next_start
  (0...H).each do |h|
    (0...W).each do |w|
      next if @magic_count[h][w] == INF

      # use magic
      si, sj = h, w
      #p [h, w]

      [*-2..2].product([*-2..2]).each do |np|
        npi = si + np[0]
        npj = sj + np[1]

        if [npi, npj] == @goal
          @magic_count[npi][npj] = @magic_count[si][sj] + 1
          return [npi, npj]
        end

        if movable?(npi, npj) && @magic_count[npi][npj] == INF
          @magic_count[npi][npj] = @magic_count[si][sj] + 1
          #p [npi, npj, @magic_count[npi][npj]]
          return [npi, npj]
        end
      end
    end
  end

  nil
end


start = @start
while true
  (si, sj) = start

  #p start

  search(si, sj)

  #p @magic_count

  if @magic_count[Dh-1][Dw-1] != INF
    break
  end

  start = next_start()

  if start.nil?
    @magic_count[Dh-1][Dw-1] = -1
    break
  end
end

puts @magic_count[Dh-1][Dw-1]
