#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> words;
int L, R;
int n;
int c;
struct type {
  int l, r, ch;
};
int genaDiff[200007], petyaDiff[200007];
int play[200007];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int maxLen = 0;
  cin >> n >> c;
  for (int i = 0; i < n; i++) {
    int len;
    cin >> len;
    maxLen = max(maxLen, len);
    vector<int> word(len, 0);
    for (int j = 0; j < len; j++) {
      cin >> word[j];
      word[j]--;
    }
    words.push_back(word);
  }
  L = 0, R = c - 1;
  bool notposs = false;
  queue<type> q;
  q.push({0, n - 1, 0});
  while (!q.empty()) {
    type curr = q.front();
    int l = curr.l;
    int r = curr.r;
    int pos = curr.ch;
    bool sorted = true;
    q.pop();
    bool prefixOver = false;
    for (int i = l; i < r + 1; i++) {
      if (words[i].size() <= pos && !prefixOver)
        l++;
      else if (words[i].size() <= pos && prefixOver) {
        notposs = true;
      } else
        prefixOver = true;
    }
    for (int i = l; i < r; i++) {
      if ((words[i][pos] + L) % c > (words[i + 1][pos] + L) % c) {
        sorted = false;
        break;
      }
    }
    if (!sorted) {
      int lNew = L, rNew = R;
      int needToDial = c - ((words[l][pos] + L) % c);
      lNew = L + needToDial;
      int newPosOfLast = (words[r][pos] + lNew) % c;
      int maxAllowed = c - 1 - newPosOfLast;
      rNew = lNew + maxAllowed;
      L = max(L, lNew);
      R = min(R, rNew);
      if (R < L) {
        notposs = true;
      }
      sorted = true;
      for (int i = l; i < r; i++) {
        if ((words[i][pos] + L) % c > (words[i + 1][pos] + L) % c)
          sorted = false;
      }
      if (!sorted) {
        notposs = true;
      }
    }
    if (notposs) {
      cout << -1;
      return 0;
    } else {
      int from = l, curr = l;
      for (int i = l + 1; i < r + 1; i++) {
        if (words[i][pos] == words[i - 1][pos])
          curr++;
        else {
          if (from != curr) {
            type t = {from, curr, pos + 1};
            from = curr + 1;
            curr = from;
            q.push(t);
          } else {
            from++;
            curr++;
          }
        }
      }
      if (from != curr) {
        type t = {from, curr, pos + 1};
        q.push(t);
      }
    }
  }
  cout << L;
  return 0;
}
