每种情况的答案几乎不变,除了:

  • 某一块变高成为「山峰」。
  • 某一块变高使得旁边不再是「山峰」。
  • 某一块变矮使得自己不再是「山峰」。
  • 某一块变矮使得旁边成为「山峰」。

直接分类讨论即可。

#include <bits/stdc++.h>
using namespace std;
int h[1012][1012];
int main()
{
	ios::sync_with_stdio(0);
	int n, m, A;
	cin >> n >> m >> A;
	long long ans = 0;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
				cin >> h[i][j];
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
		{
			int ok = 0;
			ok += 8 * (h[i][j] > h[i][j - 1]);
			ok += 4 * (h[i][j] > h[i][j + 1]);
			ok += 2 * (h[i][j] > h[i - 1][j]);
			ok += 1 * (h[i][j] > h[i + 1][j]);
			switch (ok)
			{
				case 15:
				{
					ans += 1ll * n * m * A % 998244353;
					if (h[i][j - 1]) ans -= max(A - h[i][j] + 1, 0);
					if (h[i][j + 1]) ans -= max(A - h[i][j] + 1, 0);
					if (h[i - 1][j]) ans -= max(A - h[i][j] + 1, 0);
					if (h[i + 1][j]) ans -= max(A - h[i][j] + 1, 0);
					ans -= min(max(max(h[i][j - 1], h[i][j + 1]), max(h[i - 1][j], h[i + 1][j])), A);
					break;
				}
				case 7:
				{
					ans += max(A - h[i][j - 1], 0);
					ans += min(h[i][j] - 1, A);
					break;
				}
				case 11:
				{
					ans += max(A - h[i][j + 1], 0);
					ans += min(h[i][j] - 1, A);
					break;
				}
				case 13:
				{
					ans += max(A - h[i - 1][j], 0);
					ans += min(h[i][j] - 1, A);
					break;
				}
				case 14:
				{
					ans += max(A - h[i + 1][j], 0);
					ans += min(h[i][j] - 1, A);
					break;
				}
				default:
				{
					ans += max(A - max(max(h[i][j - 1], h[i][j + 1]), max(h[i - 1][j], h[i + 1][j])), 0);
					break;
				}
			}
		}
	cout << (ans % 998244353 + 998244353) % 998244353 << endl;
	return 0;
}