#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, m;
int x, y;
int a[N], b[N];
int f[N];
int main() {
  scanf("%d%d", &n, &m);
  scanf("%d", &x);
  for (int i(1); i <= (x); ++i) scanf("%d", a + i);
  for (int op(2); op <= (n); ++op) {
    scanf("%d", &y);
    for (int j(1); j <= (y); ++j) scanf("%d", b + j);
    int z = min(x, y);
    int fg = 1;
    for (int j(1); j <= (z); ++j)
      if (a[j] != b[j]) {
        fg = 0;
        break;
      }
    if (fg) {
      if (x > y)
        return 0 * puts("-1");
      else {
        x = y;
        for (int j(1); j <= (x); ++j) a[j] = b[j];
        continue;
      }
    }
    int p = 0, q = 0;
    for (int j(1); j <= (z); ++j)
      if (a[j] != b[j]) {
        p = a[j];
        q = b[j];
        break;
      }
    if (p < q) {
      int l = m + 1 - q;
      int r = m - p;
      ++f[l], --f[r + 1];
    } else {
      int l = 0;
      int r = m - p;
      ++f[l], --f[r + 1];
      l = m + 1 - q;
      r = m;
      ++f[l], --f[r + 1];
    }
    x = y;
    for (int j(1); j <= (x); ++j) a[j] = b[j];
  }
  for (int i(1); i <= (m); ++i) f[i] += f[i - 1];
  for (int i(0); i <= (m); ++i)
    if (!f[i]) return 0 * printf("%d\n", i);
  puts("-1");
  return 0;
}
