#include using namespace std; const long long MOD = 998244353; int main(){ int H, W; cin >> H >> W; vector> A(H, vector(W)); for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ if (i == 0 || i == H - 1 || j == 0 || j == W - 1){ cin >> A[i][j]; } } } bool ok = true; for (int i = 0; i < H - 1; i++){ if (abs(A[i][0] - A[i + 1][0]) > 1){ ok = false; } if (abs(A[i][W - 1] - A[i + 1][W - 1]) > 1){ ok = false; } } for (int i = 0; i < W - 1; i++){ if (abs(A[0][i] - A[0][i + 1]) > 1){ ok = false; } if (abs(A[H - 1][i] - A[H - 1][i + 1]) > 1){ ok = false; } } if (!ok){ cout << -1 << endl; } else { vector row_ng, col_ng; vector row_a, col_a; for (int i = 1; i < H - 1; i++){ if (abs(A[i][0] - A[i][W - 1]) > W - 1){ row_ng.push_back(i); row_a.push_back(abs(A[i][0] - A[i][W - 1]) > W + 1); } } for (int i = 1; i < W - 1; i++){ if (abs(A[0][i] - A[H - 1][i]) > H - 1){ col_ng.push_back(i); col_a.push_back(abs(A[0][i] - A[H - 1][i]) > H + 1); } } if (row_ng.empty() && col_ng.empty()){ cout << 1 << endl; } else { if (!col_ng.empty()){ swap(row_ng, col_ng); swap(row_a, col_a); swap(H, W); vector> A2(H, vector(W)); for (int i = 0; i < H; i++){ for (int j = 0; j < W; j++){ A2[i][j] = A[j][i]; } } A = A2; } int cnt = row_ng.size(); vector adj(cnt - 1, false); for (int i = 1; i < cnt - 1; i++){ if (row_a[i]){ adj[i - 1] = true; adj[i] = true; } } vector dec_ng(cnt - 1, false); vector inc_ng(cnt - 1, false); for (int i = 0; i < cnt - 1; i++){ if (row_ng[i + 1] - row_ng[i] == 1){ if (abs(A[row_ng[i]][0] - A[row_ng[i + 1]][W - 1]) > W){ dec_ng[i] = true; } if (abs(A[row_ng[i]][W - 1] - A[row_ng[i + 1]][0]) > W){ inc_ng[i] = true; } } } vector> dp(cnt, vector(W - 2, 0)); for (int i = 0; i < W - 2; i++){ dp[0][i] = 1; } for (int i = 0; i < cnt - 1; i++){ if (!adj[i]){ assert(!(dec_ng[i] && inc_ng[i])); if (!dec_ng[i] && !inc_ng[i]){ long long sum = 0; for (int j = 0; j < W - 2; j++){ sum += dp[i][j]; } sum %= MOD; for (int j = 0; j < W - 2; j++){ dp[i + 1][j] = sum; } } else if (dec_ng[i]){ vector S(W - 1); S[0] = 0; for (int j = 0; j < W - 2; j++){ S[j + 1] = (S[j] + dp[i][j]) % MOD; } for (int j = 0; j < W - 2; j++){ dp[i + 1][j] = S[min(j + 2, W - 2)]; } } else if (inc_ng[i]){ reverse(dp[i].begin(), dp[i].end()); vector S(W - 1); S[0] = 0; for (int j = 0; j < W - 2; j++){ S[j + 1] = (S[j] + dp[i][j]) % MOD; } for (int j = 0; j < W - 2; j++){ dp[i + 1][j] = S[min(j + 2, W - 2)]; } reverse(dp[i + 1].begin(), dp[i + 1].end()); } } else { for (int j = 0; j < W - 2; j++){ for (int k = max(j - 1, 0); k <= min(j + 1, W - 3); k++){ dp[i + 1][k] += dp[i][j]; dp[i + 1][k] %= MOD; } } } } long long ans = 0; for (int i = 0; i < W - 2; i++){ ans += dp[cnt - 1][i]; } ans %= MOD; cout << ans << endl; } } }