#include <cstdio>
#include <cstring>
#include <iostream>
#include <bitset>
#include <queue>
using namespace std;
int diss[502][502], a[502];
int fir[502], nxt[500002], to[500002], tot;
inline void add(int a, int b) {
nxt[++tot] = fir[a];
fir[a] = tot;
to[tot] = b;
}
int dis[502];
struct node {
int to, w;
bool operator < (node x) const {
return w > x.w;
}
};
int main() {
//freopen("__.in", "r", stdin);
//freopen("__.out", "w", stdout);
int m, n;
scanf("%d%d", &m, &n);
char c = getchar();
for (int i = 1; i <= m; ++i) {
c = getchar();
int tot = 0;
while (c != '\n') {
int x = 0;
while (c < '0' || c > '9') {
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 3) + (x << 1) + (c ^ '0');
c = getchar();
}
a[++tot] = x;
}
for (int j = 1; j <= tot; ++j) {
for (int k = j + 1; k <= tot; ++k) {
diss[a[j]][a[k]] = 1;
}
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (diss[i][j]) {
add(i, j);
}
}
}
memset(dis, 0x3f, sizeof dis);
dis[1] = 0;
bitset<502> bo;
priority_queue<node> team;
bo.reset();
team.push(node{1, 0});
while (!team.empty()) {
node x = team.top();
team.pop();
if (bo[x.to]) {
continue;
}
bo[x.to] = 1;
for (int i = fir[x.to]; i; i = nxt[i]) {
if (dis[to[i]] > dis[x.to] + 1) {
dis[to[i]] = dis[x.to] + 1;
team.push(node{to[i], dis[i]});
}
}
}
if (dis[n] != 0x3f3f3f3f) printf("%d\n", dis[n] - 1);
else puts("NO");
return 0;
}