#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 50;
const int maxm = 1e6 + 50;
const double eps = 1e-10;
const int max_index = 26;
const int inf = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const double PI = acos(-1.);
inline int read() {
  char c = getchar();
  while (!isdigit(c)) c = getchar();
  int x = 0;
  while (isdigit(c)) {
    x = x * 10 + c - '0';
    c = getchar();
  }
  return x;
}
int add[maxm];
std::vector<int> v[maxm];
void solve(int l, int r) {
  add[l]++;
  add[r + 1]--;
}
int main() {
  int n = read(), m = read();
  for (int i = 1; i <= n; i++) {
    int x = read();
    v[i].resize(x);
    for (int j = 0; j < x; j++) v[i][j] = read();
  }
  for (int i = 1; i < n; i++) {
    int limit = min(v[i].size(), v[i + 1].size());
    bool flag = 1;
    for (int j = 0; j < limit; j++) {
      if (v[i][j] == v[i + 1][j]) continue;
      if (v[i][j] < v[i + 1][j])
        solve(m - v[i + 1][j] + 1, m - v[i][j]);
      else
        solve(0, m - v[i][j]), solve(m - v[i + 1][j] + 1, m - 1);
      flag = 0;
      break;
    }
    if (flag && v[i].size() > v[i + 1].size()) {
      puts("-1");
      exit(0);
    }
  }
  int ans = 0;
  for (int i = 0; i < m; i++) {
    ans += add[i];
    if (ans == 0) {
      cout << i << endl;
      exit(0);
    }
  }
  puts("-1");
  return 0;
}
