#include <bits/stdc++.h>
using namespace std;
const int UNK = -1;
int n, c;
vector<int>* w;
int mn = 0;
int mx = INT_MAX;
vector<pair<int, int> > exclude;
bool solve_simple(int pos, int from, int to) {
  while (from < to && !w[from][pos]) ++from;
  for (int i = from; i < to; ++i) {
    if (!w[i][pos]) return false;
  }
  if (from + 1 >= to) return true;
  bool diff = false;
  for (int i = from + 1; i < to; ++i) {
    if (w[i][pos] != w[from][pos]) {
      diff = true;
      break;
    }
  }
  if (!diff) {
    if (w[from][pos])
      return solve_simple(pos + 1, from, to);
    else
      return true;
  }
  int cnt = 0;
  for (int i = from + 1; i < to; ++i) {
    if (w[i][pos] < w[i - 1][pos]) {
      if (cnt) return false;
      ++cnt;
    }
  }
  if (cnt && w[from][pos] <= w[to - 1][pos]) return false;
  if (w[to - 1][pos] > w[from][pos]) {
    int curr_mn = c - w[to - 1][pos] + 1;
    int curr_mx = c - w[from][pos];
    exclude.push_back(make_pair(curr_mx, curr_mn));
  } else {
    int curr_mn = c - w[from][pos] + 1;
    int curr_mx = c - w[to - 1][pos];
    mn = max(mn, curr_mn);
    mx = min(mx, curr_mx);
    if (mn > mx) return false;
  }
  for (int i = from + 1, range_start = from; i <= to; ++i) {
    if (i == to || w[i][pos] != w[range_start][pos]) {
      bool ok = solve_simple(pos + 1, range_start, i);
      if (!ok) return false;
      range_start = i;
    }
  }
  return true;
}
bool solve(int pos, int from, int to) { return solve_simple(pos, from, to); }
int main(int argc, char* argv[]) {
  ios::sync_with_stdio(false);
  cin >> n >> c;
  w = new vector<int>[n];
  for (int i = 0; i < n; ++i) {
    int L;
    cin >> L;
    w[i].resize(L + 1);
    for (int j = 0; j < L; ++j) {
      int curr;
      cin >> curr;
      w[i][j] = curr;
    }
    w[i][L] = 0;
  }
  mx = c - 1;
  bool ok = solve(0, 0, n);
  if (!ok || mn > mx) {
    cout << -1 << endl;
    return 0;
  }
  vector<bool> vc(c);
  for (int i = mn; i <= mx; ++i) vc[i] = true;
  sort(exclude.begin(), exclude.end());
  for (int i = 0, prev_left = -1, prev_right = -1; i < exclude.size(); ++i) {
    int left = exclude[i].second;
    int right = exclude[i].first;
    if (prev_left == -1 && prev_right == -1) {
      for (int j = left; j <= right; ++j) vc[j] = false;
    } else {
      if (left > prev_right + 1) {
        for (int j = left; j <= right; ++j) vc[j] = false;
        prev_left = left;
      } else {
        for (int j = left; j < prev_left; ++j) vc[j] = false;
        for (int j = prev_right + 1; j <= right; ++j) vc[j] = false;
        prev_left = min(left, prev_left);
      }
    }
    prev_right = right;
  }
  for (int i = mn; i <= mx; ++i) {
    if (vc[i]) {
      cout << i << endl;
      return 0;
    }
  }
  cout << -1 << endl;
  return 0;
}
