program Project1;

type matrix = array[1..2000,1..2000] of longint;
  dimensions = record
    width, height: longint;
  end;

var i, j, k, n, x, y: longint;
  m: matrix;
  p: boolean;
  sl: dimensions;

begin
  read(n);
  readln(k);
  x:=0;
  for i:=1 to n do
  for j:=1 to n do
  if j=n then readln(m[i,j]) else read(m[i,j]);
  y:=m[i,j];
  with sl do begin
    width:=1;
    height:=1;
  end;
  p:=true;
  for i:=1 to n do
  if m[i,1]=y then sl.height:=sl.height+1
  else break;
  for i:=1 to sl.height do begin
    for j:=1 to n do if m[i,j]<>y then
       p:=false;
    if not p then break else sl.width:=sl.width+1;
  end;
  if p or (j=n) then x:=1;
  p:=true;
  i:=0;
  j:=0;
  while p do begin
    i:=i+1;
    j:=j+1;
    if (i>sl.width) or (j>sl.height) then begin
      if y=m[i,j] then p:=false;
    end;
  end;
  if not p then x:=0
  else if (sl.height=n) or (sl.width=n) then begin
    if (sl.height=n) and (sl.width=n) then x:=1 else x:=2;
  end else x:=1;
  writeln(x);
end.