#include <bits/stdc++.h>
using namespace std;
int g[505][505], m, n, v;
string s, t;
void init()
{
memset(g, 0x3f, sizeof(g));
for (int i = 1; i <= n; i++)
g[i][i] = 0;
}
int main()
{
cin >> m >> n;
init();
// cin.ignore();
getline(cin, s);
while (m--)
{
getline(cin, s);
stringstream ss(s);
vector<int> a;
while (ss >> v)
a.push_back(v);
for (int i = 0; i < a.size() - 1; i++)
for (int j = i + 1; j < a.size(); j++)
g[a[i]][a[j]] = 1;
}
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
if (g[1][n] == g[0][0])
cout << "NO";
else
cout << g[1][n] - 1;
return 0;
}