#include #include using namespace std; #ifdef LOCAL #include #define OUT(...) debug_print::multi_print(#__VA_ARGS__, __VA_ARGS__) #else #define OUT(...) (static_cast(0)) #endif int main(){ int h, w; cin >> h >> w; vector a, b, c, d; for(int i = 0; i < w; i++){ int v; cin >> v; a.push_back(v); if(i == 0)c.push_back(v); if(i == w - 1)d.push_back(v); } for(int i = 1; i < h - 1; i++){ int vl, vr; cin >> vl >> vr; c.push_back(vl); d.push_back(vr); } for(int i = 0; i < w; i++){ int v; cin >> v; b.push_back(v); if(i == 0)c.push_back(v); if(i == w - 1)d.push_back(v); } using modint = atcoder::modint998244353; modint ans = 1; for(int _ = 0; _ < 2; _++){ swap(h, w); swap(a, c); swap(b, d); bool ok = true; for(int i = 0; i < w; i++){ if(abs(a[i] - b[i]) >= h){ ok = false; } if(i < w - 1){ if(abs(a[i] - a[i + 1]) >= 2 || abs(b[i] - b[i + 1]) >= 2){ cout << -1 << endl; return 0; } } } if(ok)continue; vectordp; for(int i = 0; i < w; i++){ if(abs(a[i] - b[i]) < h){ if(!dp.empty()){ ans *= accumulate(dp.begin(), dp.end(), modint(0)); dp.clear(); } } else{ if(dp.empty()){ dp.assign(h - 2, 1); } else{ vector ndp(h - 1, 0); for(int j = 0; j < h - 2; j++){ int lj = max(0, j - 1); int rj = min(h - 2, j + 2); if(abs(b[i - 1] - a[i]) <= h){ ndp[0] += dp[j]; ndp[lj] -= dp[j]; } ndp[lj] += dp[j]; ndp[rj] -= dp[j]; if(abs(a[i - 1] - b[i]) <= h){ ndp[rj] += dp[j]; ndp[h - 2] -= dp[j]; } } for(int j = 0; j < h - 2; j++){ ndp[j + 1] += ndp[j]; } ndp.pop_back(); dp.swap(ndp); } } } } cout << ans.val() << endl; }