### constant

MAX_INT = (1 << 30)
DXYS = [[1, 0], [0, -1], [-1, 0], [0, 1]]

### main

while true
  $w, $h = gets.strip.split(' ').map{|s| s.to_i}
  $wh = $w * $h
  break if $w == 0 && $h == 0

  start = nil
  goal = nil
  brds = []

  for y in (0...$h)
    hl = gets.strip
    for x in (0...$w)
      pos = y * $w + x
      case hl[x]
      when '.'
        brds[pos] = -1
      when '#'
        brds[pos] = nil
      when 'X'
        brds[pos] = 'X'
      when 'S'
        start = pos
        brds[pos] = -1
      when 'G'
        goal = pos
        brds[pos] = -1
      end
    end
  end

  nice = 0
  ices = []

  for y in (0...$h)
    for x in (0...$w)
      pos = y * $w + x
      if brds[pos] == 'X'
        ices[nice] = 1
        brds[pos] = nice
        q = [pos]

        while ! q.empty?
          pos0 = q.shift
          x0 = pos0 % $w
          y0 = pos0 / $w

          for dxy in DXYS
            x1 = x0 + dxy[0]
            y1 = y0 + dxy[1]
            pos1 = y1 * $w + x1
            if x1 >= 0 && x1 < $w && y1 >= 0 && y1 < $h && brds[pos1] == 'X'
              ices[nice] += 1
              brds[pos1] = nice
              q << pos1
            end
          end
        end

        nice += 1
      end
    end
  end

  ices.map!{|k| k / 2 }

  #p brds
  #p ices

  dists = $wh.times.map{Hash.new(MAX_INT)}
  dists[start][ices] = 0
  q = [[start, ices]]

  while ! q.empty?
    #p q

    nd = q.min{|a, b| dists[a[0]][a[1]] <=> dists[b[0]][b[1]]}
    q.delete nd

    pos, ics = nd
    break if pos == goal

    x = pos % $w
    y = pos / $w

    for dxy in DXYS
      x0 = x + dxy[0]
      y0 = y + dxy[1]

      if x0 >= 0 && x0 < $w && y0 >= 0 && y0 < $h
        pos0 = y0 * $w + x0
        ic = brds[pos0]
        next if ic.nil?

        if ic >= 0
          next if ics[ic] <= 0
          ics0 = ics.clone
          ics0[ic] -= 1
        else
          ics0 = ics
        end

        d0 = dists[pos][ics] + 1
        if dists[pos0][ics0] > d0
          dists[pos0][ics0] = d0
          q << [pos0, ics0]
        end
      end
    end
  end
  #p dists

  puts dists[goal].values.min
end