def find_pos(board, n)
  @h.times do |y|
    @w.times do |x|
      return [x, y] if board[y][x] == n
    end
  end
end

def in_check(x, y)
  0 <= x && x < @w && 0 <= y && y < @h
end

def can_visit(cx, cy, mx, my, board)
  visited = @h.times.map{ [false] * @w }
  visited[my][mx] = true
  queue = [[mx, my]]
  until queue.empty?
    x, y = queue.shift
    @dir.each do |dx, dy|
      xx = x + dx; yy = y + dy
      if in_check(xx, yy) && !visited[yy][xx] &&
        board[yy][xx] != 1 && !(cx == xx && cy == yy)
        queue << [xx, yy]
        visited[yy][xx] = true
      end
    end
  end
  visited
end

def move(cx, cy, mx, my, board)
  ret = []
  move_pos = can_visit(cx, cy, mx, my, board)
  @dir.each_with_index do |(dx, dy), i|
    x = cx + dx; y = cy + dy
    if in_check(x, y) && move_pos[y][x]
      ret << i
    end
  end
  ret
end

def solve(cx, cy, mx, my, board)
  used = @h.times.map{ @w.times.map{ [false] * 4 } }
  queue = []
  move(cx, cy, mx, my, board).each do |i|
    queue << [cx, cy, i, 0]
    used[cy][cx][i] = true
  end
  until queue.empty?
    x, y, i, n = queue.shift
    return n if x == @gx && y == @gy
    move(x, y, x + @dir[i][0], y + @dir[i][1], board).each do |ii|
      xx = x + @dir[(ii + 2) % 4][0]
      yy = y + @dir[(ii + 2) % 4][1]
      if in_check(xx, yy) && !used[yy][xx][ii] && board[yy][xx] != 1
        queue << [xx, yy, ii, n + 1]
        used[yy][xx][ii] = true
      end
    end
  end
  -1
end

@dir = [[-1, 0], [0, 1], [1, 0], [0, -1]]
loop do
  @w, @h = gets.split.map(&:to_i)
  break if @w == 0
  board = @h.times.map{ gets.split.map(&:to_i) }

  cx, cy = find_pos(board, 2)
  @gx, @gy = find_pos(board, 3)
  mx, my = find_pos(board, 4)

  puts solve(cx, cy, mx, my, board)
end