#include <bits/stdc++.h>
using namespace std;
vector<int> g[500500];
int k[500500], seg[1000100];
int main() {
  ios_base::sync_with_stdio(0);
  int n, c;
  cin >> n >> c;
  for (int i = 0; i < n; i++) {
    cin >> k[i];
    g[i].resize(k[i]);
    for (int j = 0; j < k[i]; j++) cin >> g[i][j];
  }
  int kl = 0;
  for (int i = 1; i < n; i++) {
    bool f = 0;
    for (int j = 0; j < min(k[i], k[i - 1]); j++) {
      int l1 = 0, r1 = c - 1;
      if (g[i][j] == g[i - 1][j]) continue;
      if (g[i - 1][j] < g[i][j]) {
        r1 = c - g[i][j];
        seg[0]++;
        seg[r1 + 1]--;
        l1 = c - g[i - 1][j] + 1;
        r1 = l1 + c - (g[i][j] + l1 - c);
        seg[l1]++;
        seg[min(c, r1)]--;
      } else {
        l1 = c - g[i - 1][j] + 1;
        r1 = c - g[i][j];
        seg[l1]++;
        seg[r1 + 1]--;
      }
      f = 1;
      break;
    }
    if (!f && k[i - 1] > k[i]) {
      cout << -1 << endl;
      return 0;
    }
    if (f) kl++;
  }
  if (seg[0] == kl) {
    cout << 0 << endl;
    return 0;
  }
  for (int i = 1; i < c; i++) {
    seg[i] += seg[i - 1];
    if (seg[i] == kl) {
      cout << i << endl;
      return 0;
    }
  }
  cout << -1 << endl;
  return 0;
}
