#include <bits/stdc++.h>
#define IOS ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
using namespace std;
typedef long long ll;
int n, m, dp[1010][1010];
string str;
vector<int> way;
void to_vector(string t)
{
way.clear();
int now = 0;
t += " ";
for(auto it : t)
{
if(it == ' ')
{
way.push_back(now);
now = 0;
}
else now = now * 10 + it - 48;
}
return;
}
void Floyd()
{
for(int k = 1; k <= n; k ++)
{
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
if(i != j && i != k && j != k) dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]);
}
}
}
return;
}
int main()
{
IOS;
memset(dp, 0x3f, sizeof dp);
scanf("%d %d\n", &m, &n);
while(m --)
{
getline(cin, str);
to_vector(str);
for(int j = 1; j <= way.size(); j ++)
{
dp[j][j] = 0;
for(int k = j; k < way.size(); k ++) dp[way[j - 1]][way[k]] = 1;
}
}
Floyd();
if(dp[1][n] >= 0x3f3f3f3f) cout << "NO\n";
else cout << dp[1][n] - 1 << endl;
return 0;
}