### constant

MAX_W = MAX_H = 7
INF = 1 << 30
DXYS = [[1, 0], [0, -1], [-1, 0], [0, 1]]

### subroutines

def paint(w, h, flds)
  cls = (w * h).times.map{0}
  cl = 1

  for y0 in (0...h)
    for x0 in (0...w)
      pos0 = y0 * w + x0
      if flds[pos0] && cls[pos0] == 0
        cls[pos0] = cl
        q = [pos0]

        while ! q.empty?
          u = q.shift
          ux = u % w
          uy = u / w
          DXYS.each do |dx, dy|
            vx = ux + dx
            vy = uy + dy
            v = vy * w + vx
            if vx >= 0 && vx < w && vy >= 0 && vy < h &&
               flds[v] && cls[v] == 0
              cls[v] = cl
              q << v
            end
          end
        end

        cl += 1
      end
    end
  end
  
  cls
end

### main

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

  wh = w * h
  flds = wh.times.map{true}
  cpos = gpos = mpos = nil
  
  for y in (0...h)
    line = gets.split.map(&:to_i)
    for x in (0...w)
      pos = y * w + x
      case line[x]
      when 1
        flds[pos] = false
      when 2
        cpos = pos
      when 3
        gpos = pos
      when 4
        mpos = pos
      end
    end
  end
  #p flds
  #p [cpos, gpos, mpos]
  
  edges = wh.times.map{wh.times.map{wh.times.map{false}}}
  
  for y in (0...h)
    for x in (0...w)
      cpos0 = y * w + x
      if flds[cpos0]
        flds[cpos0] = false
        cls = paint(w, h, flds)
        flds[cpos0] = true

        for pos0 in (0...wh)
          cl0 = cls[pos0]
          next if cl0 == 0
          for pos1 in (pos0...wh)
            if cls[pos1] == cl0
              edges[cpos0][pos0][pos1] = edges[cpos0][pos1][pos0] = true
            end
          end
        end
      end
    end
  end
  #p edges
  
  dists = wh.times.map{wh.times.map{INF}}
  dists[cpos][mpos] = 0
  q = [[cpos, mpos]]

  while ! q.empty?
    uc, um = q.shift
    break if uc == gpos

    ucx = uc % w
    ucy = uc / w
    nvd = dists[uc][um] + 1

    DXYS.each do |dx, dy|
      vcx = ucx + dx
      vcy = ucy + dy
      vc = vcy * w + vcx

      vmx = ucx - dx
      vmy = ucy - dy
      vm = vmy * w + vmx
      #p [vcx, vcy, vmx, vmy, flds[vc], flds[vm], edges[uc][um][vm]]
      
      if vcx >= 0 && vcx < w && vcy >= 0 && vcy < h && flds[vc] &&
         vmx >= 0 && vmx < w && vmy >= 0 && vmy < h && flds[vm] &&
         edges[uc][um][vm]
        if dists[vc][uc] >= INF
          dists[vc][uc] = nvd
          q << [vc, uc]
          #p [vcx, vcy, ucx, ucy, dists[vc][uc]]
        end
      end
    end
  end

  mind = dists[gpos].min
  puts (mind >= INF ? -1 : mind)
end