
const
  mn: array [1..12] of String[10] = (
   'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL',
   'MAY', 'JUNE', 'JULY', 'AUGUST',
   'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER');
  ml: array [1..12] of Integer = (
   31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var
  C: array [1..28, 1..73] of Char;
  P: array [1..10] of String[10];
  N, M: Integer;

procedure Month(m: Integer; var day: Integer);
var
  i, x, y, yy: Integer;
begin
  x := ((m - 1) mod 4) * 18 + 2;
  yy := ((m - 1) div 4) * 9 + 2;
  for i := 1 to Length(mn[m]) do C[yy, x + i] := mn[m, i];
  y := yy + day + 1;
  for i := 1 to ml[m] do begin
    if i > 9 then C[y, x] := Chr(i div 10 + 48);
    C[y, x + 1] := Chr(i mod 10 + 48);
    day := (day + 1) mod 7;
    Inc(y);
    if day = 0 then begin Inc(x, 3); y := yy + 1; end;
  end;
end;

procedure Year(y: Integer; var day: Integer);
var
  i: Integer;
begin
  FillChar(C, SizeOf(C), '.');
  if (y mod 4 = 0) and ((y mod 100 <> 0) or (y mod 400 = 0)) then
    ml[2] := 29
  else
    ml[2] := 28;
  for i := 1 to 12 do
    Month(i, day);
end;

function Try(x, y: Integer): Boolean;
var
  i, j: Integer;
begin
  Try := false;
  for i := 1 to M do
    for j := 1 to N do
      if C[y + i - 1, x + j - 1] <> P[i, j] then exit;
  Try := true;
end;

var
  i, j, d, y: Integer;
  b, z: Boolean;
  f: Text;
begin
//  Assign(f, 'input.txt'); Reset(f);
  Readln(N, M);
  for i := 1 to M do
    Readln(P[i]);
//  Close(f);
//  Assign(f, 'output.txt'); Rewrite(f);
  d := 0; z := false;
  for y := 1900 to 2100 do begin
    Year(y, d);
    {if y = 2002 then begin
      Writeln;
      for i := 1 to 28 do
        Writeln(C[i]);
    end;}
    b := false;
    for i := 1 to High(C) - M + 1 do begin
      for j := 1 to High(C[i]) - N + 1 do begin
        b := Try(j, i);
        if b then break;
      end;
      if b then break;
    end;
    if b then Writeln(y);
    z := z or b;
  end;
  if not z then Writeln(0);
//  Close(f);
end.
