#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > mas;
set<int> good;
int main() {
  int n, c;
  scanf("%d %d", &n, &c);
  for (int i = 0; i < c; i++) good.insert(i);
  mas.resize(n);
  for (int i = 0; i < n; i++) {
    int k;
    scanf("%d", &k);
    mas[i].resize(k);
    for (int j = 0; j < k; j++) scanf("%d", &mas[i][j]), mas[i][j]--;
  }
  for (int i = 0; i < n - 1; i++) {
    int len = min((int)(mas[i]).size(), (int)(mas[i + 1]).size());
    for (int j = 0; j < len; j++) {
      if (mas[i][j] < mas[i + 1][j]) {
        int from = (-mas[i][j] + c) % c;
        int to = (c - mas[i + 1][j] - 1 + c) % c;
        if (from <= to) {
          while (true) {
            set<int>::iterator it = good.lower_bound(0);
            if (it != good.end() && *it < from) {
              good.erase(it);
            } else
              break;
          }
          while (true) {
            set<int>::iterator it = good.upper_bound(to);
            if (it != good.end() && *it > to) {
              good.erase(it);
            } else
              break;
          }
        } else {
          while (true) {
            set<int>::iterator it = good.upper_bound(to);
            if (it != good.end() && *it > to && *it < from) {
              good.erase(it);
            } else
              break;
          }
        }
        break;
      } else if (mas[i][j] > mas[i + 1][j]) {
        int from = (c - mas[i][j] + c) % c;
        int to = (c - mas[i + 1][j] - 1 + c) % c;
        if (from <= to) {
          while (true) {
            set<int>::iterator it = good.lower_bound(0);
            if (it != good.end() && *it < from) {
              good.erase(it);
            } else
              break;
          }
          while (true) {
            set<int>::iterator it = good.upper_bound(to);
            if (it != good.end() && *it > to) {
              good.erase(it);
            } else
              break;
          }
        } else {
          while (true) {
            set<int>::iterator it = good.upper_bound(to);
            if (it != good.end() && *it > to && *it < from) {
              good.erase(it);
            } else
              break;
          }
        }
        break;
      }
    }
  }
  if (good.empty()) {
    printf("-1\n");
    return 0;
  }
  int minval = *good.begin();
  if (minval == -1e9) minval = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < (int)(mas[i]).size(); j++)
      mas[i][j] = ((mas[i][j] + minval) % c + c) % c;
  for (int i = 0; i < n - 1; i++) {
    if (mas[i] > mas[i + 1]) {
      printf("-1\n");
      return 0;
    }
  }
  printf("%d\n", minval);
  return 0;
}
