R, C = gets.split.map(&:to_i) SY, SX = gets.split.map(&:to_i) GY, GX = gets.split.map(&:to_i) G = R.times.map { gets.chomp.chars } DY = [-1, 0, 1, 0] DX = [0, 1, 0, -1] queue = [] queue << [SY - 1, SX - 1, 0] visited = Array.new(R) { Array.new(C, false) } until queue.empty? y, x, dist = queue.shift if y == GY - 1 && x == GX - 1 puts dist exit end next if visited[y][x] visited[y][x] = true 4.times do |i| ny = y + DY[i] nx = x + DX[i] next if G[ny][nx] == '#' queue << [ny, nx, dist + 1] end end