#include <bits/stdc++.h>
using namespace std;
long long n, c;
vector<long long> s[500100];
vector<pair<long long, long long> > ss;
bool can = true;
long long sd = 0;
void solve(int k, long long st, long long en) {
  if (st >= en) return;
  long long dd = 0;
  long long nst = st;
  for (int i = st; i <= en; i++) {
    if (s[i].size() <= k) {
      if (dd == 1) {
        can = false;
        return;
      }
    } else {
      if (dd == 0) {
        nst = i;
      }
      dd = 1;
    }
  }
  if (dd == 0) return;
  st = nst;
  bool bg = false;
  for (int i = st + 1; i <= en; i++) {
    if (s[i][k] < s[st][k]) {
      bg = true;
      break;
    }
  }
  long long ad = 0;
  if (bg) {
    ad = (c - s[st][k]) + 1;
  }
  long long last = 0;
  vector<pair<long long, long long> > rr;
  long long nnst = st;
  long long nned = -1;
  long long mmax = 1;
  long long ff = 0;
  for (int i = st; i <= en; i++) {
    long long d = s[i][k] + ad;
    if (d > c) {
      d -= c;
    }
    if (i == st) ff = d;
    if (d > last) {
      if (last != 0) {
        rr.push_back({nnst, i - 1});
      }
      nnst = i;
    } else if (d < last) {
      can = false;
      return;
    }
    if (i == en) {
      mmax = d;
      rr.push_back({nnst, i});
    }
    last = d;
  }
  long long mk = ad + (c - mmax);
  if (mmax == ff) {
    mk = 2 * c;
  } else if (ad == 0) {
    long long ad2 = c - s[st][k] + 1;
    long long mmax2 = s[en][k] + ad2;
    if (mmax2 > c) mmax2 -= c;
    long long mk2 = ad2 + (c - mmax2);
    ss.push_back({ad2, mk2});
  }
  sd++;
  ss.push_back({ad, mk});
  for (int i = 0; i < rr.size(); i++) {
    solve(k + 1, rr[i].first, rr[i].second);
  }
  return;
}
long long fd[2000100];
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> c;
  for (int i = 0; i < n; i++) {
    long long kk;
    cin >> kk;
    for (int j = 0; j < kk; j++) {
      long long a;
      cin >> a;
      s[i].push_back(a);
    }
  }
  solve(0, 0, n - 1);
  if (!can) {
    cout << -1 << endl;
    return 0;
  }
  for (int i = 0; i < ss.size(); i++) {
    fd[ss[i].first]++;
    fd[ss[i].second + 1]--;
  }
  long long tot = 0;
  long long ls = -1;
  for (int i = 0; i <= c * 2; i++) {
    tot += fd[i];
    if (tot == sd) {
      cout << i << endl;
      return 0;
    }
  }
  cout << ls << endl;
  return 0;
}
