#include <iostream>
#include <string>
#include <algorithm>
#include <queue>
#include <cstring>
#define x first
#define y second
using namespace std;
const int N = 5e2 + 10;
int n , m , g[N][N] , dist[N];
int stop[N];
int bfs()
{
queue<int> q;
q.push(1);
dist[1] = 0;
while(q.size())
{
int t = q.front();
q.pop();
for(int i = 1 ; i <= n ; i++){
if(g[t][i] && dist[i] > dist[t] + 1){
dist[i] = dist[t] + 1;
q.push(i);
}
}
}
return dist[n];
}
int main()
{
cin >> m >> n;
string road;
memset(dist , 0x3f , sizeof dist);
getchar();
while(m--)
{
getline(cin , road);
int cnt = 0;
for(int i = 0 ; i < road.size() ; ++i)
{
if(road[i] != ' ') {
int res = 0;
int j;
for(j = i ; j < road.size() && road[j] != ' '; ++j){
res = res * 10 + road[j] - '0';
}
i = j;
stop[++cnt] = res;
}
}
for(int i = 1 ; i <= cnt ; ++i){
for(int j = i + 1 ; j <= cnt ; ++j){
g[stop[i]][stop[j]] = 1;
}
}
}
int ans = bfs();
if(ans == 0x3f3f3f3f) puts("NO");
else cout << ans - 1 << endl;
return 0;
}