### constant

INF = 1 << 30

BLK_X = -1
BLK_T = 10

LEG_L = 0
LEG_R = 1

DXYS = [
  [[1, -2],
   [1, -1], [2, -1],
   [1,  0], [2,  0], [3, 0],
   [1,  1], [2,  1],
   [1,  2]],
  [[-1, -2],
   [-1, -1], [-2, -1],
   [-1,  0], [-2,  0], [-3, 0],
   [-1,  1], [-2,  1],
   [-1,  2]]
]

### main

loop do
  w, h = gets.split.map(&:to_i)
  break if (w | h) == 0

  blks = h.times.map{[]}
  starts = []

  for y in (0...h)
    line = gets.strip.split
    for x in (0...w)
      case line[x]
      when 'S'
        starts << [x, y]
        blks[y][x] = 0
      when 'T'
        blks[y][x] = BLK_T
      when 'X'
        blks[y][x] = BLK_X
      else
        blks[y][x] = line[x].to_i
      end
    end
  end
  #p blks
  #p starts

  dists = h.times.map{w.times.map{2.times.map{INF}}}
  q = []

  starts.each do |x, y|
    dists[y][x][LEG_L] = dists[y][x][LEG_R] = 0
    q += [[x, y, LEG_L], [x, y, LEG_R]]
  end

  min_dist = INF

  while ! q.empty?
    u = q.min{|a, b| dists[a[1]][a[0]][a[2]] <=> dists[b[1]][b[0]][b[2]]}
    q.delete(u)

    ux, uy, ulr = u
    ud = dists[uy][ux][ulr]
    vlr = (ulr ^ 1)

    DXYS[ulr].each do |dx, dy|
      vx = ux + dx
      vy = uy + dy

      if vx >= 0 && vx < w && vy >= 0 && vy < h
        blk = blks[vy][vx]
        next if blk == BLK_X

        if blk == BLK_T
          min_dist = ud if min_dist > ud
          next
        end

        vd = dists[vy][vx][vlr]
        nvd = ud + blk

        if vd > nvd
          q << [vx, vy, vlr] if dists[vy][vx][vlr] >= INF
          dists[vy][vx][vlr] = nvd
        end
      end
    end
  end

  puts (min_dist >= INF ? -1 : min_dist)
end