const maxn=500;
var m,n,h,t:integer;
at:array[0..maxn,0..maxn]of boolean;
p,st:array[0..maxn]of integer;
hs:array[0..maxn]of boolean;
///////////////
procedure add(x:integer);
var i:integer;
begin
inc(t);
p[t]:=x;
st[x]:=st[p[h]]+1;
hs[x]:=false;
if x=n then
begin
write(st[x]-1);
halt;
end;
end;
///////////////
procedure init;
var i,j,k:integer;
a:array[0..maxn]of integer;
begin
fillchar(at,sizeof(at),false);
readln(m,n);
for i:=1 to m do
begin
j:=0;
while not(eoln) do
begin
inc(j);
read(a[j]);
for k:=1 to j-1 do
at[a[k],a[j]]:=true;
end;
readln;
end;
end;
///////////////
procedure main;
var i:integer;
begin
fillchar(hs,sizeof(hs),true);
t:=1; h:=0;
p[1]:=1; st[1]:=0; hs[1]:=false;
while h<t do
begin
inc(h);
for i:=1 to n do
if at[p[h],i] and hs[i] then add(i);
end;
end;
///////////////
procedure print;
begin
write('NO');
end;
///////////////
begin
init;
main;
print;
end.