class Array
  def swap!(a, b)
    raise ArgumentError unless a.between?(0, self.count-1) && b.between?(0, self.count-1)
    self[a], self[b] = self[b], self[a]
    self
  end
  def swap(a, b)
    self.dup.swap!(a, b)
  end
  def print_all()
      self.map{|x| puts x.join(" ")}
  end
end

N,M = gets.split(" ").map(&:to_i)
ary = N.times.map{gets.split.map(&:to_i).sort!}
ary_line = ary.map{|x| x.map{|y| y = (y-1)/M}}

1.upto(N-1) do |i|
    ary_line[0...i].transpose[0...M-1].each_with_index do |val,key|
        target = 1+key+ (ary_line[i][key+1...M].index((((0..N-1).to_a - val) & ary_line[i][key+1...M]).max)).to_i
        ary_line[i].swap!(key, target)
        ary[i].swap!(key, target)
    end
end
ary.print_all
ary.transpose.map{|x| x.sort}.transpose.print_all
