#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const int maxn = 2e6 + 10, maxm = 2e6 + 10;
const long long INF = 0x3f3f3f3f, mod = 10;
int casn, n, m, k;
vector<int> v[maxn];
int sum[maxn];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (int i = 1; i <= n; ++i) {
    cin >> k;
    while (k--) {
      int t;
      cin >> t;
      v[i].push_back(t);
    }
  }
  for (int i = 1; i <= n - 1; ++i) {
    int l = 0, r = m - 1;
    int lena = v[i].size();
    int lenb = v[i + 1].size();
    int flag = 0;
    for (int j = 0; j <= min(lena, lenb) - 1; ++j) {
      int a = v[i][j];
      int b = v[i + 1][j];
      if (a < b) {
        flag = 1;
        sum[0]++;
        sum[m - b + 1]--;
        sum[m - a + 1]++;
        break;
      } else if (a > b) {
        flag = 1;
        sum[m - a + 1]++, sum[m - b + 1]--;
        break;
      }
    }
    if (!flag && lena > lenb) {
      cout << -1 << endl;
      return 0;
    }
    if (!flag) sum[0]++;
  }
  for (int i = 1; i <= m + 2; ++i) sum[i] += sum[i - 1];
  for (int i = 0; i <= m + 1; ++i)
    if (sum[i] >= n - 1) {
      cout << i << endl;
      return 0;
    }
  cout << -1 << endl;
}
