#include <bits/stdc++.h>
using namespace std;
const int nm = 500010;
int n, m;
vector<int> a[nm];
int sl[nm];
int l, r;
vector<pair<int, int> > b;
int rmax[nm];
void xuli(int vt) {
  int i;
  for (i = 0; i < a[vt].size() && i < a[vt + 1].size(); ++i) {
    if (a[vt][i] != a[vt + 1][i]) break;
  }
  if (i >= a[vt].size()) {
    return;
  }
  if (i >= a[vt + 1].size()) {
    cout << "-1\n";
    exit(0);
  }
  if (a[vt][i] > a[vt + 1][i]) {
    l = max(l, a[vt + 1][i] + 1);
    r = min(r, a[vt][i]);
  } else {
    b.push_back(make_pair(a[vt][i], a[vt + 1][i] + 1));
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &sl[i]);
    for (int j = 1; j <= sl[i]; ++j) {
      int x;
      scanf("%d", &x);
      a[i].push_back(x);
    }
  }
  l = 1;
  r = m;
  for (int i = 1; i < n; ++i) {
    xuli(i);
  }
  if (l > r) {
    cout << "-1\n";
    return 0;
  }
  if (b.size() == 0) {
    cout << (m - l + 1) % m << "\n";
    return 0;
  }
  sort(b.begin(), b.end());
  rmax[0] = b[0].second;
  for (int i = 1; i < b.size(); ++i) {
    rmax[i] = max(rmax[i - 1], b[i].second);
  }
  for (int i = l; i <= r; ++i) {
    int j = lower_bound(b.begin(), b.end(), make_pair(i, -1)) - b.begin();
    if (j == 0 || rmax[j - 1] <= i) {
      cout << (m - i + 1) % m << "\n";
      return 0;
    }
  }
  cout << "-1\n";
}
