#include <iomanip>
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
#include <set>
#include "queue"
//#include <multiset>
#include <map>
#include <utility>
#include <numeric>
#include "random"
#ifndef __clang__
#include <bits/stdc++.h>
#endif
using namespace std;

#define all(x) (x).begin(), (x).end()
#define int long long

const int mod = 998244353;
vector<int> dp1, dp2;
int solve(vector<int> &a, int b, int c);
int solve(vector<int> &a, int c);

int solve(vector<int> &a, int c) {
    if (a.empty())
        return 0;
    if (a.back() == c) {
        a.pop_back();
        return solve(a, c);
    }
    int res = -1;
    for (int i = 0; i < 3; ++i) {
        if (i != c and i != a.back())
            res = i;
    }
    int n = a.size();
    int pp = a.back();
    a.pop_back();
    solve(a, res);
exit(12);
}
int solve(vector<int> &a, int b, int c) {
    //if (b == c)
    //    return solve(a, c);
    if (a.empty())
        return 0;
    if (a.back() == b) {
        a.pop_back();
        return solve(a, c, c);
    }
    int res = -1;
    for (int i = 0; i < 3; ++i) {
        if (i != b and i != a.back())
            res = i;
    }
    int n = a.size();
    int pp = a.back();
    a.pop_back();
    int ans = solve(a, res,res);
    if (abs(b-pp) == 1) {
        ans += 1;
        if (abs(res-c) == 2)
            ans += dp2[n-1];
        if (abs(res-c) == 1)
            ans += dp1[n-1];
    }
    if (abs(b - pp) == 2) {
        ans += 1 + dp2[n-1]+1;
        res = 2-res;
        if (abs(res-c) == 2)
            ans += dp2[n-1];
        if (abs(res-c) == 1)
            ans += dp1[n-1];
    }
    return ans % mod;
}
void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    vector<int> b(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
        a[i]--;
    }
    for (int i = 0; i < n; ++i) {
        cin >> b[i];
        b[i]--;
    }
    while (!a.empty() and a.back() == b.back()) {
        a.pop_back();
        b.pop_back();
    }
    if (a.empty()) {
        cout << "0\n";
        return;
    }
    int mv = a.back();
    if (mv < b.back())
        mv++;
    else
        mv--;
    int res = -1;
    for (int i = 0; i < 3; ++i) {
        if (i != mv and i != a.back())
            res = i;
    }
    int ans = solve(a, mv, res) + solve(b, mv, res);
    cout << ans % mod << '\n';
}

signed main() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    int N = 1e5 + 30;
    dp1.assign(N, {});
    dp2.assign(N, {});
    dp1[0] = 0;
    dp2[0] = 0;
    for (int i = 1; i < N; ++i) {
        dp2[i] = (3 * dp2[i-1] + 2) % mod;
        dp1[i] = (dp2[i-1] + 1 + dp1[i-1]) % mod;
    }
    int t = 1;
    cin >> t;
    while (t--) {
        solve();
    }
}
