local ior = io.input() local w, h = ior:read("*n", "*n", "*l") local sh, sw, gh, gw = ior:read("*n", "*n", "*n", "*n", "*l") local str = "" local map = {} local function getindex(xh, xw) return (xh - 1) * w + xw end local cue = {} local tasks, done = 1, 0 local bcue = {} local btasks, bdone = 0, 0 local startfound = false for i = 1, h do str = ior:read() for j = 1, w do local idx = getindex(i, j) if(str:sub(j, j) == ".") then if(not startfound) then table.insert(cue, idx) map[idx] = 0 startfound = true else map[idx] = -2 end else map[idx] = -1 end end end local ret_cand = 40 local function walk(src, dst) if (map[dst] == -2) then map[dst] = 0 tasks = tasks + 1 table.insert(cue, dst) elseif(map[dst] == -1) then map[dst] = 1 btasks = btasks + 1 table.insert(bcue, dst) end end local function smash(src, dst) if (map[dst] == -1) then map[dst] = map[src] + 1 btasks = btasks + 1 table.insert(bcue, dst) elseif(0 < map[dst]) then if(map[src] + 1 < map[dst]) then map[dst] = map[src] + 1 btasks = btasks + 1 table.insert(bcue, dst) end elseif(map[dst] == -2) then ret_cand = math.min(ret_cand, map[src]) end end while(done < tasks) do done = done + 1 local idx = cue[done] if(w < idx) then walk(idx, idx - w) end if(idx <= (h - 1) * w) then walk(idx, idx + w) end if(idx % w ~= 0) then walk(idx, idx + 1) end if(idx % w ~= 1) then walk(idx, idx - 1) end end while(bdone < btasks) do bdone = bdone + 1 local idx = bcue[bdone] if(w < idx) then smash(idx, idx - w) end if(idx <= (h - 1) * w) then smash(idx, idx + w) end if(idx % w ~= 0) then smash(idx, idx + 1) end if(idx % w ~= 1) then smash(idx, idx - 1) end end print(ret_cand)