#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long f = 1, x = 0;
  char s = getchar();
  while (s < '0' || s > '9') {
    if (s == '-') f = -1;
    s = getchar();
  }
  while (s >= '0' && s <= '9') {
    x = x * 10 + (s - '0');
    s = getchar();
  }
  return x * f;
}
const int jzm = 1000000007;
int n, m, i, j, s, o, k;
vector<int> a[500005];
int c[1000005];
void addt(int l, int r) {
  c[l]++;
  c[r + 1]--;
}
void solve(int a, int b) {
  if (a == b)
    addt(0, m - 1);
  else if (a == -1) {
    addt(0, m - 1);
  } else if (b == -1) {
    return;
  } else if (a < b) {
    addt(0, m - b);
    addt(m - a + 1, m - 1);
  } else {
    addt(m - a + 1, m - b);
  }
}
int main() {
  n = read();
  m = read();
  for (int i = 1; i <= n; i++) {
    k = read();
    while (k--) {
      a[i].push_back(read());
    }
    a[i].push_back(-1);
  }
  for (int i = 1; i < n; i++) {
    for (int j = 0; j < a[i].size() && j < a[i + 1].size(); j++) {
      if (a[i][j] != a[i + 1][j] || a[i][j] == -1) {
        solve(a[i][j], a[i + 1][j]);
        break;
      }
    }
  }
  int ans = -1;
  for (int i = 0; i < m; i++) {
    if (i) c[i] += c[i - 1];
    if (c[i] == n - 1) {
      ans = i;
      break;
    }
  }
  printf("%d\n", ans);
  return 0;
}
