#include <bits/stdc++.h>
using i64 = long long;
template <class T = long long int>
class Bit {
 private:
  T len;
  T *arr;

 public:
  Bit(T l, T initialValue = 0) : len(l) {
    arr = new T[l + 1];
    for (T i = 0; i < l + 1; i++) {
      arr[i] = initialValue;
    }
  }
  ~Bit() { delete[] arr; }
  void update(T a, T newval) {
    for (T x = a; x <= len; x += x & -x) arr[x] += newval;
  }
  T query(T a) const {
    T ret = 0;
    for (T x = a; x > 0; x -= x & -x) ret += arr[x];
    return ret;
  }
};
int main() {
  i64 n;
  scanf("%lld", &n);
  const i64 mod = 998244353;
  if (n == 1) {
    printf("0\n");
    return 0;
  }
  std::vector<i64> fact(n + 1);
  fact[0] = 1;
  for (i64 i = 1; i <= n; i++) fact[i] = fact[i - 1] * i % mod;
  std::vector<i64> p(n + 1);
  p[0] = 1;
  for (int i = 2; i <= n; i++) {
    p[i] = (i - 1) * (p[i - 1] + p[i - 2]) % mod;
  }
  for (int i = 1; i <= n; i++) {
    p[i] = p[i - 1] * p[n] % mod;
  }
  std::vector<std::vector<i64>> d(n + 10, std::vector<i64>(n + 10, 1));
  for (int i = 1; i <= n; i++) {
    d[i][0] = fact[i];
    for (int j = 1; j <= i + 1; j++) {
      d[i][j] = (d[i][j - 1] + mod - d[i - 1][j - 1]) % mod;
    }
  }
  std::vector<std::vector<i64>> a(n, std::vector<i64>(n));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      scanf("%lld", &a[i][j]);
    }
  }
  i64 ret = 0;
  for (int r = 0; r < n; r++) {
    Bit<> b1(n + 10), b2(n + 10);
    i64 k = 0;
    for (int i = 1; i <= n; i++) {
      b2.update(i, 1);
    }
    for (int i = 0; i < n; i++) {
      auto curr = a[r][i];
      if (r) {
        if (b2.query(a[r - 1][i]) - b2.query(a[r - 1][i] - 1) > 0) {
          b2.update(a[r - 1][i], -1);
        } else {
          k--;
        }
        auto used = b1.query(curr);
        auto rem = curr - 1 - used;
        if (a[r - 1][i] < curr &&
            b1.query(a[r - 1][i]) - b1.query(a[r - 1][i] - 1) == 0)
          rem--;
        b1.update(curr, 1);
        auto inc = b2.query(curr - 1);
        ret = (ret +
               inc * d[n - i - 1][n - i - 2 - k] % mod * p[n - r - 1] % mod) %
              mod;
        ret = (ret + (rem - inc) * d[n - i - 1][n - i - 1 - k] % mod *
                         p[n - r - 1] % mod) %
              mod;
        if (b2.query(curr) - b2.query(curr - 1) > 0) {
          b2.update(curr, -1);
          k++;
        }
      } else {
        auto used = b1.query(curr);
        auto rem = curr - 1 - used;
        b1.update(curr, 1);
        ret = (ret + rem * fact[n - i - 1] % mod * p[n - 1] % mod) % mod;
      }
    }
  }
  printf("%lld\n", ret);
  return 0;
}
