注意到答案是 a1,1a_{1, 1} 的因数,而 a1,1a_{1, 1} 最多只有 6464 个因数,逐个判断即可。

#include <bits/stdc++.h>
using namespace std;
const int N = 1000 + 12;
int a[N][N], b[N][N];
int main()
{
	freopen("walk.in", "r", stdin);
	freopen("walk.out", "w", stdout);
	ios::sync_with_stdio(0);
	int n, V;
	cin >> n >> V;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			cin >> a[i][j];
	for (int s = V; s >= 1; s--)
	{
		if (a[1][1] % s) continue;
		b[1][1] = s;
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
			{
				if (b[i][j] != s) continue;
				if (i != n && a[i + 1][j] % s == 0) b[i + 1][j] = s;
				if (j != n && a[i][j + 1] % s == 0) b[i][j + 1] = s;
			}
		if (b[n][n] == s)
		{
			cout << s << endl;
			return 0;
		}
	}
	return 0;
}