#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 10;
const int maxm = 1e6 + 10;
vector<int> a[maxm];
int n, c;
int l[maxm], f[maxm];
void solve() {
  ios::sync_with_stdio(0);
  cin >> n >> c;
  int x, y;
  for (int i = 0; i < n; i++) {
    cin >> l[i];
    for (int j = 0; j < l[i]; j++) {
      cin >> x;
      a[i].push_back(x);
    }
  }
  for (int i = 0; i < n - 1; i++) {
    int sz = min(l[i], l[i + 1]);
    int j;
    for (j = 0; j < sz; j++) {
      if (a[i][j] != a[i + 1][j]) break;
    }
    if (j == sz) {
      if (l[i] <= l[i + 1]) {
        f[0]++, f[c]--;
      }
    } else {
      x = a[i][j], y = a[i + 1][j];
      if (x > y) {
        int t = c - x + 1;
        x = 1;
        y = y + t;
        if (y > c) y -= c;
        int t1 = c - y;
        f[t]++;
        f[t + t1 + 1]--;
      } else {
        int last = y;
        int t = c - y + 1;
        y = 1;
        f[0]++;
        f[t]--;
        x = x + t;
        if (x > c) x -= c;
        int t1 = c - x + 1;
        y = y + t1;
        if (y > c) y -= c;
        if (y >= last) continue;
        int t2 = last - y;
        f[t + t1]++;
        f[t + t1 + t2]--;
      }
    }
  }
  if (f[0] == n - 1) {
    cout << 0 << endl;
    return;
  }
  for (int i = 1; i < c; i++) {
    f[i] += f[i - 1];
    if (f[i] == n - 1) {
      cout << i << endl;
      return;
    }
  }
  cout << -1 << endl;
}
int main() {
  solve();
  return 0;
}
