program polosa4;

{$APPTYPE CONSOLE}
{$o-}
uses
  SysUtils;
const nmax=10;
type
Tperest=array [1..nmax] of integer;
var a,b:array[1..nmax] of string[100];
    estj:array[1..9] of boolean;
    c:Tperest;
    s,smax,s1,s2,st:string[100];
    i,j,n,q,m,t,r:integer;
    cifr:string[1];
procedure sledperest (const n:integer;var x: Tperest);
var k,i,j:integer;
begin
   k:=n-1;
   while (k>0)and(x[k]>x[k+1]) do k:=k-1;
   if k>0 then begin
      j:=n; while x[k]>x[j] do j:=j-1;
      i:=x[k]; x[k]:=x[j]; x[j]:=i;
      k:=k+1; j:=n;
      while k<j do begin
         i:=x[k]; x[k]:=x[j]; x[j]:=i;
         k:=k+1; j:=j-1;
      end
   end;
end;

begin
// reset(input,'input.txt');
//rewrite(output,'output.txt');
 readln(n,m);
 for i:=1 to n do
   readln(a[i]);
 for i:=1 to n do begin
   if pos('9',a[i])>0 then begin estj[9]:=true; continue end;
   if pos('8',a[i])>0 then begin estj[8]:=true;continue end;
   if pos('7',a[i])>0 then begin estj[7]:=true;continue end;
   if pos('6',a[i])>0 then begin estj[6]:=true;continue end;
   if pos('5',a[i])>0 then begin estj[5]:=true;continue end;
   if pos('4',a[i])>0 then begin estj[4]:=true;continue end;
   if pos('3',a[i])>0 then begin estj[3]:=true;continue end;
   if pos('2',a[i])>0 then begin estj[2]:=true;continue end;
   if pos('1',a[i])>0 then begin estj[1]:=true;continue end;
  end;
 q:=1;
 for i:=1 to n do begin
   c[i]:=i;       //?????? ???????????? 123...n
   q:=q*i;      //?????????? ????????????
 end;
 smax:='';
 for i:=1 to m*n do smax:=smax+'0';
 for i:=1 to q do begin
    s:='';
    for j:=1 to n do
     s:=s+a[c[j]];
    s:=s+s;
    for r:=9 downto 1 do
     if estj[r] then break;//????? ??????? ?????
     cifr:=inttostr(r);  //?????????? ?? ? ??????
    for t:=1  to m*n do    //???? ????? ????????
     if s[t]=cifr then begin  //???? ????? ?????
     s1:=copy(s,t,m*n-t+1);
     s2:=copy(s,1,t-1);
     st:=s1+s2;
     if st>smax then  //?????????? ???? ?????
      smax:=st;
     end;
    sledperest(n,c);
  end;
//??????? ?? ?????????
 for j:=1 to m do
 for i:=1 to n do begin
   s:=a[i];
   b[j]:=b[j]+s[j];
  end;
 q:=1;
 for i:=1 to m do begin
   c[i]:=i;       //?????? ???????????? 123...m
   q:=q*i;      //?????????? ????????????
 end;

 for i:=1 to q do begin
    s:='';
    for j:=1 to m do
     s:=s+b[c[j]];
    s:=s+s;
    for r:=9 downto 1 do
     if estj[r] then break;//????? ??????? ?????
     cifr:=inttostr(r);  //?????????? ?? ? ??????
    for t:=1  to m*n do    //???? ????? ????????
     if s[t]=cifr then begin  //???? ????? ?????
     s1:=copy(s,t,m*n-t+1);
     s2:=copy(s,1,t-1);
     st:=s1+s2;
     if st>smax then  //?????????? ???? ?????
      smax:=st;
     end;
    sledperest(m,c);
  end;
  write(smax);
 end.

