### constant

INF = 1 << 30
HP = 6

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

### main

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

  wh = w * h
  
  flds = wh.times.map{0}
  spt = gpt = nil
  pts = []
  
  for y in (0...h)
    line = gets.split.map(&:to_i)
    for x in (0...w)
      pt = y * w + x
      case line[x]
      when 0
        flds[pt] = -1
      when 2
        spt = pt
      when 3
        gpt = pt
      when 4
        pts << pt
      end
    end
  end
  pts.unshift(spt)
  pts << gpt

  pts.each_with_index{|pt, i| flds[pt] = i + 1}
  #p flds
  #p pts

  n = pts.length
  edges = n.times.map{n.times.map{nil}}
  nbrs = n.times.map{[]}
  
  pts.each_with_index do |pti, i|
    dists = wh.times.map{INF}
    dists[pti] = 0
    q = [pti]

    while ! q.empty?
      upt = q.shift

      ux = upt % w
      uy = upt / w
      nvd = dists[upt] + 1

      DXYS.each do |dx, dy|
        vx = ux + dx
        vy = uy + dy
        vpt = vy * w + vx
        if vx >= 0 && vx < w && vy >= 0 && vy < h && flds[vpt] >= 0
          vd = dists[vpt]
          if vd >= INF
            dists[vpt] = nvd
            if flds[vpt] > 0
              j = flds[vpt] - 1
              edges[i][j] = edges[j][i] = nvd
              nbrs[i] << j
              nbrs[j] << i
            end
            q << vpt if nvd < (HP - 1)
          end
        end
      end
    end
    #p dists
  end

  nbrs = (0...n).map{|i| nbrs[i].uniq.sort}
  #p edges
  #p nbrs

  times = n.times.map{INF}
  times[0] = 0
  q = [0]

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

    break if u == n - 1

    ut = times[u]
    
    for v in nbrs[u]
      nvt = ut + edges[u][v]
      vt = times[v]
      if vt > nvt
        q << v if vt >= INF
        times[v] = nvt
      end
    end
  end

  t = times[n - 1]
  puts (t >= INF) ? -1 : t
end