#include <bits/stdc++.h>
using namespace std;
int n, now, b[2009], c[2][2009], a[2009][2009], dp[2009][2009], pw[2009];
int read() {
  int x = 0;
  char ch = getchar();
  bool flag = 0;
  while (ch < '0' || ch > '9') {
    if (ch == '-') flag = 1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return flag ? -x : x;
}
long long readll() {
  long long x = 0;
  char ch = getchar();
  bool flag = 0;
  while (ch < '0' || ch > '9') {
    if (ch == '-') flag = 1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return flag ? -x : x;
}
void ins(int *c, int x) {
  for (; x <= n; x += x & -x) c[x]++;
}
int getsum(int *c, int x) {
  int ans = 0;
  for (; x; x ^= x & -x) ans += c[x];
  return ans;
}
void add(int x) {
  if (!x) return;
  b[x]++;
  if (b[x] == 2) {
    now++;
    ins(c[0], x);
  }
}
int calc(int x, int y) {
  if (y < 0 || y > x) return 0;
  return dp[x][y];
}
int main() {
  scanf("%d", &n);
  int i, j;
  for (i = 1; i <= n; i++)
    for (j = 1; j <= n; j++) scanf("%d", &a[i][j]);
  for (i = dp[0][0] = 1; i <= n; i++)
    for (j = 0; j <= i; j++) {
      if (j <= 1)
        dp[i][j] = (long long)dp[i - 1][max(0, j - 1)] * (i - j) % 998244353;
      else
        dp[i][j] = ((long long)dp[i - 1][j - 2] * (j - 1) +
                    (long long)dp[i - 1][j - 1] * (i - j)) %
                   998244353;
    }
  for (i = pw[0] = 1; i <= n; i++)
    pw[i] = (long long)pw[i - 1] * dp[n][n] % 998244353;
  int ans = 0;
  for (i = 1; i <= n; i++) {
    memset(b, 0, sizeof(b));
    memset(c, 0, sizeof(c));
    now = 0;
    for (j = n; j; j--) {
      add(a[i - 1][j]);
      add(a[i][j]);
      ins(c[1], a[i][j]);
      int x = getsum(c[0], a[i][j] - 1), y = getsum(c[1], a[i][j] - 1) - x;
      (ans = (ans +
              ((long long)pw[n - i] *
               calc(n - j, now - (b[a[i - 1][j]] == 2) - 1) % 998244353 * x)) %
             998244353);
      (ans =
           (ans + ((long long)pw[n - i] *
                   calc(n - j, now - (b[a[i - 1][j]] == 2)) % 998244353 * y)) %
           998244353);
      if (b[a[i - 1][j]] == 2 && a[i - 1][j] && a[i - 1][j] < a[i][j])
        (ans = (ans +
                ((long long)(998244353 - pw[n - i]) * calc(n - j, now - 2))) %
               998244353);
    }
  }
  printf("%d\n", ans);
  return 0;
}
