var
i , tot , n , m , x , t , k , j , head , tail : longint;
a : array[0..501] of record
y , next : longint;
end;
v , lk : array[0..501] of longint;
b : array[0..501] of boolean;
h : array[0..2001] of longint;
procedure install(x , y : longint);
begin
inc(tot);
a[tot].y := y;
a[tot].next := lk[x];
lk[x] := tot;
end;
begin
readln(n , m);
tot := 0;
for i := 1 to n do
begin
t := 0;
while not eoln() do
begin
read(x);
inc(t);
v[t] := x;
end;
readln;
for k := 1 to t - 1 do
for j := k + 1 to t do
install(v[k] , v[j]);
end;
fillchar(v , sizeof(v) , 100);
fillchar(b , sizeof(b) , 0);
h[1] := 1; v[1] := 0;
b[1] := true;
head := 0; tail := 1;
while head < tail do
begin
inc(head);
t := lk[h[head]];
b[h[head]] := false;
while t <> 0 do
begin
if v[a[t].y] > v[h[head]] + 1 then
begin
v[a[t].y] := v[h[head]] + 1;
if not b[a[t].y] then
begin
inc(tail);
h[tail] := a[t].y;
b[a[t].y] := true;
end;
end;
t := a[t].next;
end;
end;
if v[m] = 1684300900 then writeln('NO') else
writeln(v[m] - 1);
end.