#include <iostream>
#include <vector>
using namespace std;

void updateTableString(const vector<int>& data, const vector<int>& cPerm,
                       const vector<int>& rPerm, vector<int>& best)
{
  int rows = rPerm.size(), cols = cPerm.size();
  double smaller = false;
  
  for(int c = 0; c < cols; ++c)
    for(int r = 0; r < rows; ++r)
    {
      int price = data[rPerm[r] + cPerm[c]*rows];
      
      if(smaller || (smaller = (price < best[r + c*rows])))
        best[r + c*rows] = price;
      else if(price > best[r + c*rows])
        return;
    }
}

int main()
{
  int n, I = 0;
  for(cin >> n; n > 0; --n)
  {
    int cols, rows;
    cin >> cols >> rows;
      
    vector<int> data(cols*rows), cPerm(cols), rPerm(rows);
    for(int i = 0; i < cols*rows; ++i)
      cin >> data[i];
    for(int i = 0; i < cols; ++i)
      cPerm[i] = i;
    for(int i = 0; i < rows; ++i)
      rPerm[i] = i;
      
    vector<int> best = data;
    do
    {
      do
        updateTableString(data, cPerm, rPerm, best);
      while(next_permutation(rPerm.begin(), rPerm.end()));
    }while(next_permutation(cPerm.begin(), cPerm.end()));
    
    cout << "Scenario #" << ++I << ":\n";
    for(int i = 0; i < rows*cols; ++i)
      cout << (i > 0 ? " " : "") << best[i];
    cout << endl << endl;
  }
}
