#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
const int N = 2000 + 20, mod = 998244353;
int n, a[N][N];
int dp[N][N], save[N], fac[N], ans;
int d[N];
int fen[N], gg[N];
void pre() {
  for (int i = 0; i < N; i++)
    for (int j = 0; j <= i; j++) {
      if (!i)
        dp[i][j] = 1;
      else if (!j)
        dp[i][j] = 1ll * dp[i - 1][j] * i % mod;
      else {
        dp[i][j] = 1ll * (i - j) * dp[i - 1][j - 1] % mod;
        if (j > 1)
          dp[i][j] = (dp[i][j] + 1ll * (j - 1) * dp[i - 1][j - 2]) % mod;
      }
    }
  fac[0] = 1;
  for (int i = 1; i < N; i++) fac[i] = 1ll * fac[i - 1] * i % mod;
}
inline void add(int fen[N], int p, int val) {
  for (p++; p < N; p += p & -p) fen[p] += val;
}
inline int get(int fen[N], int p) {
  int ans = 0;
  for (; p; p -= p & -p) ans += fen[p];
  return ans;
}
int main() {
  ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  pre();
  cin >> n;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) cin >> a[i][j], a[i][j]--;
  save[0] = 1;
  for (int i = 1; i <= n; i++) save[i] = 1ll * save[i - 1] * dp[n][n] % mod;
  for (int i = 0; i < n; i++) {
    memset(fen, 0, sizeof fen);
    memset(gg, 0, sizeof gg);
    for (int j = 0; j < n; j++) add(fen, j, 1), add(gg, j, 1), d[j] = 2;
    int second = save[n - i - 1];
    if (!i) {
      for (int j = 0; j < n; j++) {
        ans = (ans + 1ll * get(fen, a[i][j]) * fac[n - j - 1] % mod * second) %
              mod;
        add(fen, a[i][j], -1);
      }
      continue;
    }
    int cur = n;
    for (int j = 0; j < n; j++) {
      int dad = a[i - 1][j];
      d[dad]--;
      if (d[dad]) add(gg, dad, -1), cur--;
      int A = get(gg, a[i][j]), B = get(fen, a[i][j]) - A;
      if (d[dad] && dad < a[i][j]) B--;
      ans = (ans + 1ll * A * dp[n - j - 1][cur - 1] % mod * second) % mod;
      ans = (ans + 1ll * B * dp[n - j - 1][cur] % mod * second) % mod;
      int c = a[i][j];
      d[c]--;
      if (d[c]) add(gg, c, -1), cur--;
      add(fen, c, -1);
    }
  }
  cout << ans << '\n';
}
