#include<bits/stdc++.h> using namespace std; int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);} #define MOD 1000000007 #define MOD2 998244353 #define INF (1<<29) #define LINF (1LL<<60) #define EPS (1e-10) #define PI 3.1415926535897932384626433832795028 #define ll long long int bool codejam = 1; void topologicalSortUtil(int v, bool visited[], stack<int> &Stack,vector<vector<int>> adj) { visited[v] = true; vector<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack,adj); Stack.push(v); } void topologicalSort(ll n,vector<vector<int>> adj) { ll V=n; stack<int> Stack; bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; for (int i = 0; i < V; i++) if (visited[i] == false and adj[i].size()!=0) topologicalSortUtil(i, visited, Stack,adj); while (Stack.empty() == false) { cout << (char) ('A' + Stack.top()); Stack.pop(); } } void printOrder(vector<string>& words, int n, int alpha) { vector<vector<int>> adj(26,vector<int>{}); for (int i = 0; i < words.size(); i++) { for(int j=0;j<words[i].size()-1;j++) adj[words[i][j]-'A'].push_back(words[i][j+1]-'A'); } topologicalSort(n,adj); } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ll t; cin>>t; ll tc = 1; while(t--){ if(codejam){ cout<<"Case #"<<tc++<<": "; } ll r,c; cin>>r>>c; vector<vector<char>> a(r,vector<char>(c,'A')); map<int,map<ll,ll>> m; unordered_set<char> alpha; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ cin>>a[i][j]; alpha.insert(a[i][j]); m[j][a[i][j]-'A']++; } } bool failed = false; for(int j=0;j<c;j++){ for(int row = r-1;row>=0;row--){ int count = 1; int count2 = 0; while(row>0 and a[row-1][j] == a[row][j]){ count++; row--; } row = r-1; while(row>=0){ if(a[row][j]==a[r-1][j]) count2++; row--; } if(count != count2){ cout<<-1<<endl; failed = true; break; } } if(failed) break; } if(!failed){ vector<string> words; for(int col = 0; col<c;col++){ string word = ""; set<char> seen; for(int row=r-1;row>=0;row--){ if(seen.find(a[row][col])==seen.end()) word+=a[row][col]; seen.insert(a[row][col]); } words.push_back(word); } printOrder(words,words.size(),26); cout<<endl; } } }