#include <bits/stdc++.h>
using namespace std;
const int maxn = 1000005, maxm = 30;
const long long mod = 1000000007;
int n, m;
vector<int> v[maxn];
int ck[maxn] = {0};
void solve() {
  int i, j;
  for (i = 0; i < n - 1; i++) {
    int l = v[i].size(), t = v[i + 1].size();
    for (j = 0; j < l && j < t; j++) {
      if (v[i][j] != v[i + 1][j]) break;
    }
    if (j == t && j < l) {
      printf("-1\n");
      return;
    }
    if (j == l) continue;
    if (v[i][j] < v[i + 1][j]) {
      ck[m - v[i + 1][j] + 1]++;
      ck[m - v[i][j] + 1]--;
    } else {
      ck[0]++;
      ck[m - v[i][j] + 1]--;
      ck[m]--;
      ck[m - v[i + 1][j] + 1]++;
    }
  }
  for (i = 1; i < m; i++) ck[i] += ck[i - 1];
  for (i = 0; i < m; i++)
    if (ck[i] == 0) {
      printf("%d\n", i);
      return;
    }
  printf("-1\n");
}
int main() {
  int i, j;
  scanf("%d %d", &n, &m);
  for (i = 0; i < n; i++) {
    int l;
    scanf("%d", &l);
    for (j = 0; j < l; j++) {
      int x;
      scanf("%d", &x);
      v[i].push_back(x);
    }
  }
  solve();
  return 0;
}
