#include <bits/stdc++.h>
using namespace std;
pair<int, int> y[1000010];
int l[1000010], n, m, k = 0, aa[1000010];
vector<int> a[1000010];
void doc() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    cin >> l[i];
    a[i].push_back(-1);
    for (int j = 1; j <= l[i]; j++) {
      int x;
      cin >> x;
      a[i].push_back(x);
    }
  }
}
void xl() {
  for (int i = 1; i < n; i++) {
    int vt = 0;
    for (int j = 1; j <= min(l[i], l[i + 1]); j++) {
      if (a[i][j] != a[i + 1][j]) {
        vt = j;
        break;
      }
    }
    if (vt == 0 && l[i] > l[i + 1]) {
      cout << -1;
      exit(0);
    }
    if (vt > 0) {
      int x1 = a[i + 1][vt], x2 = a[i][vt];
      if (x1 > x2) {
        y[++k].first = m - x1 + 1;
        y[k].second = m - x2;
      } else {
        y[++k].first = 0;
        y[k].second = m - x2;
        y[++k].first = m - x1 + 1;
        y[k].second = m - 1;
        if (y[k].second < y[k].first) k--;
      }
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  doc();
  xl();
  if (k == 0) {
    cout << 0;
    return 0;
  }
  sort(y + 1, y + k + 1);
  if (y[1].first != 0) {
    cout << 0;
    return 0;
  }
  int r1 = y[1].second;
  for (int i = 2; i <= k; i++) {
    if (y[i].first > r1 + 1) {
      cout << r1 + 1;
      return 0;
    }
    r1 = max(r1, y[i].second);
  }
  if (r1 == m - 1)
    cout << -1;
  else
    cout << r1 + 1;
}
