/*
换车最少次数 = 坐车最少次数-1
1 2 3 4 5 6 7
每坐一次车cnt+1(那么从2→1 2→3 2→5 的权重都是1 代表坐一次车就可以到)
总共的边数最多 = C{2}{N}2 <= C{2}{500}2
所有权重都是1 可以用BFS来求最短距离
*/
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<sstream>
using namespace std;
typedef pair<int,int> PII;
const int N=510,M=250000;
int m,n;
int h[N],e[M],ne[M],w[M],idx;
int dist[N];
int station[N];
bool st[N];
void add(int a,int b,int c)
{
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
int spfa()
{
memset(dist,0x3f,sizeof dist);
queue<int> q;
q.push(1);
st[1] = true;
dist[1] = 0;
while(q.size())
{
int ver = q.front();
q.pop();
st[ver] = false;
for(int i=h[ver];i!=-1;i=ne[i])
{
int j = e[i];
if(dist[j]>dist[ver]+w[i])
{
dist[j] = dist[ver]+w[i];
if(!st[j])
{
st[j]=true;
q.push(j);
}
}
}
}
if(dist[n]==0x3f3f3f3f) return -1;
return dist[n];
}
int dijkstra()
{
memset(dist,0x3f,sizeof dist);
priority_queue<PII,vector<PII>,greater<PII>> heap;
heap.push({0,1});
dist[1] = 0;
while(heap.size())
{
int ver = heap.top().second;
int d = heap.top().first;
heap.pop();
if(st[ver]) continue;
st[ver] = true;
for(int i=h[ver];i!=-1;i=ne[i])
{
int j = e[i];
if(dist[j]>d+w[i])
{
dist[j] = d+w[i];
heap.push({dist[j],j});
}
}
}
if(dist[n]==0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
memset(h,-1,sizeof h);//漏了初始化h了 导致死循环TLE
cin >> m >> n;
string line;
getline(cin,line);
while(m--)
{
getline(cin,line);
stringstream ssin(line);
int tot=0,p;
while(ssin>>p) station[tot++]=p;
for (int i = 0; i < tot; i ++ )//从前往后
for (int j = i + 1; j < tot; j ++ )
add(station[i],station[j],1);//加边加成add(i,j,1)了 查bug查了2h qwq
}
// int res = spfa();
int res = dijkstra();
if(res==-1) cout << "NO" << endl;
else cout << res-1 << endl;
// cout << dijkstra() << endl;
return 0;
}