#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1000005;
int mlc[NMAX];
void add(int x, int y) {
  if (x > y) {
    return;
  }
  mlc[x]++;
  mlc[y + 1]--;
}
int main() {
  cin.sync_with_stdio(false);
  int n, m;
  scanf("%d%d", &n, &m);
  vector<int> last;
  int need = 0;
  for (int i = 0; i < n; i++) {
    int sz;
    scanf("%d", &sz);
    vector<int> curr(sz);
    for (int j = 0; j < sz; j++) {
      scanf("%d", &curr[j]);
    }
    if (i) {
      int sign = 0;
      int A = -1;
      int B = -1;
      for (int j = 0; j < (int)min(curr.size(), last.size()); j++) {
        if (last[j] < curr[j]) {
          A = last[j];
          B = curr[j];
          sign = -1;
          break;
        } else if (last[j] > curr[j]) {
          A = last[j];
          B = curr[j];
          sign = 1;
          break;
        }
      }
      if (sign == 0 && curr.size() < last.size()) {
        printf("-1\n");
        return 0;
      }
      if (sign == -1) {
        add(0, m - B);
        add(m - A + 1, m - 1);
        need++;
      } else if (sign == 1) {
        add(m - A + 1, m - B);
        need++;
      }
    }
    last.clear();
    for (auto it : curr) {
      last.push_back(it);
    }
  }
  for (int i = 0; i < m; i++) {
    if (i) {
      mlc[i] += mlc[i - 1];
    }
    if (mlc[i] == need) {
      printf("%d\n", i);
      return 0;
    }
  }
  printf("-1\n");
  return 0;
}
