#include <bits/stdc++.h>
using namespace std;
int N, C;
vector<vector<int> > W;
vector<pair<int, int> > seg;
void dfs(int s, int e, int col) {
  if (s > e) return;
  if (W[s].size() == col) {
    dfs(s + 1, e, col);
    return;
  }
  for (int i = s; i <= e; i++) {
    if (W[i].size() == col) {
      seg.push_back(pair<int, int>(0, C - 1));
      return;
    }
  }
  int minp = s;
  for (int i = s; i < e; i++) {
    if (W[i][col] > W[i + 1][col]) {
      minp = i + 1;
      break;
    }
  }
  int prev = W[minp][col];
  for (int i = minp + 1; i <= e; i++) {
    if (prev > W[i][col]) {
      seg.push_back(pair<int, int>(0, C - 1));
      return;
    }
    prev = W[i][col];
  }
  for (int i = s; i < minp; i++) {
    if (prev > W[i][col]) {
      seg.push_back(pair<int, int>(0, C - 1));
      return;
    }
    prev = W[i][col];
  }
  if (minp == s)
    seg.push_back(pair<int, int>(C + 1 - W[e][col], C - W[s][col]));
  else {
    seg.push_back(pair<int, int>(0, C - W[s][col]));
    seg.push_back(pair<int, int>(C + 1 - W[e][col], C - 1));
  }
  prev = s;
  for (int i = s; i <= e; i++) {
    if (i == e || W[i][col] != W[i + 1][col]) {
      dfs(prev, i, col + 1);
      prev = i + 1;
    }
  }
}
int main() {
  scanf("%d %d", &N, &C);
  W.resize(N);
  for (int i = 0; i < N; i++) {
    int len;
    scanf("%d", &len);
    W[i].resize(len);
    for (int j = 0; j < len; j++) {
      scanf("%d", &W[i][j]);
    }
  }
  dfs(0, N - 1, 0);
  sort(seg.begin(), seg.end());
  int pos = 0;
  int mx = -1;
  for (int i = 0; i < C; i++) {
    while (pos < seg.size() && seg[pos].first <= i) {
      mx = max(mx, seg[pos].second);
      pos++;
    }
    if (mx < i) {
      printf("%d", i);
      return 0;
    }
  }
  printf("-1");
}
