#include <bits/stdc++.h>
using namespace std;
char buf[100000], *p1 = buf, *p2 = buf, ch;
int result;
inline int re() {
  ch = p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
           ? EOF
           : *p1++;
  ;
  result = 0;
  while (ch < '0' || ch > '9')
    ch = p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
             ? EOF
             : *p1++;
  ;
  while (ch >= '0' && ch <= '9')
    result = result * 10 + (ch ^ 48),
    ch = p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
             ? EOF
             : *p1++;
  ;
  return result;
}
long long f[2005], ff[2005], gg, ans, jc[2005], dp[2005][2005], res;
int a[2005][2005], n, j, i, b[2005], tmp, vis[2005], c1[2005], c2[2005],
    pos[2005][2005];
void add1(int x, int y) {
  while (x < 2005) c1[x] += y, x += (x & (-x));
}
void add2(int x, int y) {
  while (x < 2005) c2[x] += y, x += (x & (-x));
}
int sum1(int x) {
  int ret = 0;
  while (x) ret += c1[x], x -= (x & (-x));
  return ret;
}
int sum2(int x) {
  int ret = 0;
  while (x) ret += c2[x], x -= (x & (-x));
  return ret;
}
int main() {
  n = re();
  for (i = jc[0] = 1; i <= n; jc[i] = jc[i - 1] * i % 998244353, ++i)
    for (j = 1; j <= n; ++j) pos[i][a[i][j] = re()] = j;
  for (f[0] = f[2] = 1, f[3] = 2, i = 4; i <= n; ++i)
    f[i] = (f[i - 1] + f[i - 2]) * (i - 1) % 998244353;
  for (i = 1; i <= n; ++i) b[i] = a[1][i];
  for (i = 1; i <= n; ++i) {
    gg += jc[n - i] * (b[i] - 1);
    for (j = i + 1; j <= n; ++j)
      if (b[j] > b[i]) --b[j];
  }
  for (ff[0] = i = 1; i < n; ++i) ff[i] = f[n] * ff[i - 1] % 998244353;
  ans += gg % 998244353 * ff[n - 1] % 998244353;
  dp[0][0] = 1;
  for (i = 1; i <= n; ++i) {
    dp[i][0] = jc[i];
    dp[i][1] = dp[i - 1][0] * (i - 1) % 998244353;
    for (j = 2; j <= i; ++j) {
      dp[i][j] =
          (dp[i - 1][j - 1] * (i - 1) + dp[i - 2][j - 2] * (j - 1)) % 998244353;
    }
  }
  for (i = 2; i <= n; ++i) {
    memset(vis, 0, sizeof(vis));
    memset(c1, 0, sizeof(c1));
    for (j = 1; j < 2005; ++j) c2[j] = (j & (-j));
    tmp = n;
    for (res = 0, j = 1; j <= n; ++j) {
      if (!vis[a[i][j]]) add2(a[i][j], -1), --tmp;
      if (vis[a[i][j]] == 2) add1(a[i][j], -1);
      if (!vis[a[i - 1][j]]) {
        add1(a[i - 1][j], 1);
        add2(a[i - 1][j], -1);
        --tmp;
      }
      vis[a[i - 1][j]] |= 2;
      vis[a[i][j]] |= 1;
      res += (sum1(a[i][j] - 1) -
              ((a[i - 1][j] < a[i][j]) && ((vis[a[i - 1][j]] & 1) == 0))) *
             dp[n - j][tmp + ((vis[a[i][j]] & 2) == 0)];
      res +=
          (sum2(a[i][j] - 1)) * dp[n - j][tmp - 1 + ((vis[a[i][j]] & 2) == 0)];
    }
    ans += res % 998244353 * ff[n - i] % 998244353;
  }
  cout << (ans % 998244353 + 998244353) % 998244353;
}
