#include <bits/stdc++.h>
using namespace std;
const int N = 5 * 1e5 + 5;
const int M = 2e6 + 5;
vector<int> a[M], b[M];
vector<int> c[M], d[M];
int vis[M];
int n, w, cnt;
int main() {
  scanf("%d%d", &n, &w);
  w--;
  for (int i = 1; i <= n; i++) {
    int k;
    scanf("%d", &k);
    a[i].resize(k);
    for (int j = 0; j < k; j++) {
      int g;
      scanf("%d", &g);
      a[i][j] = g - 1;
    }
  }
  for (int i = 1; i < n; i++) {
    int up = min(a[i].size(), a[i + 1].size());
    bool flag = false;
    for (int j = 0; j < up; j++) {
      if (a[i][j] > a[i + 1][j]) {
        b[a[i][j]].push_back(a[i + 1][j]);
        flag = true;
        break;
      } else if (a[i][j] < a[i + 1][j]) {
        b[a[i][j]].push_back(a[i + 1][j]), flag = true;
        break;
      }
    }
    if (!flag && a[i].size() > a[i + 1].size()) {
      puts("-1");
      return 0;
    }
  }
  for (int i = 0; i < 1e6; i++) {
    if (!b[i].size()) continue;
    int mx = -1, mn = 1e6 + 5, mx2 = -1, mn2 = 1e6 + 5, add = w - i + 1;
    for (int j : b[i]) {
      mx = max(mx, j);
      mn = min(mn, j);
      mx2 = max(mx2, (j + add) % (w + 1));
      mn2 = min(mn2, (j + add) % (w + 1));
    }
    cnt++;
    if (mn > i) {
      c[0].push_back(cnt);
      d[w - mx].push_back(cnt);
      c[w - i + 1].push_back(cnt);
      d[2 * w - mx].push_back(cnt);
    } else {
      c[add].push_back(cnt);
      d[add + w - mx2].push_back(cnt);
    }
  }
  int ans = 0;
  for (int i = 0; i < 1e6; i++) {
    for (int j : c[i]) {
      if (!vis[j]) ans++;
      vis[j]++;
    }
    if (ans == cnt) {
      printf("%d\n", i);
      return 0;
    }
    for (int j : d[i]) {
      if (vis[j] == 1) ans--;
      vis[j]--;
    }
  }
  puts("-1");
  return 0;
}
