#hは高さ、wは横幅
h,w = gets.split(" ").map(&:to_i)

#スタート地点
ch,cw = gets.split(" ").map(&:to_i)

#ゴール
dh,dw = gets.split(" ").map(&:to_i)

map=[]

h.times do
    r = gets.chomp.split("")
    map.push(r)
end

class Maze
    def initialize(h,w,map)
        @height = h
        @width = w
        @maze = map
        @route = Array.new(h){Array.new(w,".")}
    end

    def seek(ch,cw)
        ch -= 1
        cw -= 1
        que=[[ch, cw]]
        @maze[ch][cw]=0
        @route[ch][cw]=0
        while que.length > 0
            y,x = que.shift
            steps = @maze[y][x].to_i + 1
            warps = @route[y][x].to_i
            (-2..2).each do |dy|
                py = y + dy
                if py >= 0 && py < @height
                    (-2..2).each do |dx|
                        px = x + dx
                        if px >= 0 && px < @width
                            warp = (dx.abs + dy.abs <= 1) ? 0 : 1
                            if @route[py][px].to_i > warps + warp || @maze[py][px] == "." || @maze[py][px] > steps
                                @maze[py][px] = steps
                                @route[py][px] = warps + warp
                                que.push([py,px])
                            end
                        end
                    end
                end
            end
        end
    end

    def goal(dh,dw)
        dh -= 1
        dw -= 1
        @maze[dh][dw] != "." ? @route[dh][dw] : -1
    end

    def show
        puts "maze"
        @maze.each do |row|
            puts row.join("")
        end
        puts "warp"
        @route.each do |row|
            puts row.join("")
        end
    end

end

maze = Maze.new(h,w,map)
maze.seek(ch,cw)
puts maze.goal(dh,dw)

