#include <bits/stdc++.h>
using namespace std;
pair<int, int> comb(pair<int, int> a, pair<int, int> b) {
  pair<int, int> res;
  if (a.first < b.first)
    res.first = b.first;
  else
    res.first = a.first;
  if (a.second > b.second)
    res.second = b.second;
  else
    res.second = a.second;
  if (res.first <= res.second)
    return res;
  else
    return pair<int, int>(-1, -1);
}
int main() {
  int n, c;
  cin >> c >> n;
  int** li;
  li = new int*[2];
  li[0] = new int[500000];
  li[1] = new int[500000];
  int l[2];
  cin >> l[0];
  for (int i = 0; i < l[0]; i++) {
    int x;
    cin >> li[0][i];
  }
  int index = 1;
  queue<pair<int, int> > qu;
  while (!qu.empty()) qu.pop();
  qu.push(pair<int, int>(0, n - 1));
  for (int i = 1; i < c; i++) {
    cin >> l[index];
    for (int j = 0; j < l[index]; j++) {
      int x;
      scanf(" %d", &(li[index][j]));
    }
    int left, right, check;
    int le = l[index];
    if (l[1 - index] < le) le = l[1 - index];
    check = 0;
    for (int j = 0; j < le; j++)
      if (li[index][j] != li[1 - index][j]) {
        left = (n - li[1 - index][j] + 1) % n;
        right = n - li[index][j];
        check = 1;
        break;
      }
    if (check == 0)
      if (l[index] >= l[1 - index]) {
        left = 0;
        right = n - 1;
      } else {
        cout << -1 << endl;
        return 0;
      }
    int tn = qu.size();
    if (tn == 0) {
      cout << -1 << endl;
      return 0;
    }
    while (tn > 0) {
      tn--;
      pair<int, int> tch, res;
      tch = qu.front();
      qu.pop();
      if (left <= right) {
        res = comb(tch, pair<int, int>(left, right));
        if (res.first != -1) {
          qu.push(res);
        }
      } else {
        res = comb(tch, pair<int, int>(left, n - 1));
        if (res.first != -1) {
          qu.push(res);
        }
        res = comb(tch, pair<int, int>(0, right));
        if (res.first != -1) {
          qu.push(res);
        }
      }
    }
    index = 1 - index;
  }
  if (qu.size() == 0)
    cout << -1 << endl;
  else
    cout << qu.front().first << endl;
  return 0;
}
