Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * author: heWhoCooks
- * created: 2024-12-27 19:50:38
- **/
- #include <bits/stdc++.h>
- using namespace std;
- mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
- #define NeedForSpeed \
- ios_base::sync_with_stdio(false); \
- cin.tie(NULL); \
- cout.tie(NULL);
- #define int long long
- #define all(x) (x).begin(), (x).end()
- typedef vector<int> vi;
- typedef vector<bool> vb;
- typedef vector<vi> vvi;
- typedef vector<pair<int, int>> vpi;
- #define f first
- #define s second
- #define pb push_back
- #define pf push_front
- #define yes cout << "YES" << endl
- #define no cout << "NO" << endl
- #define endl "\n"
- #define M_PI 3.14159265358979323846L
- const int mod = 1e9 + 7;
- const int INF = 2e18;
- int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
- const int N = 105;
- int dp[N][N], grid[N][N];
- void solve()
- {
- int n, m;
- cin >> n >> m;
- for (int i = 1; i <= n; i++)
- {
- for (int j = 1; j <= m; j++)
- {
- cin >> grid[i][j];
- }
- }
- vi divisors;
- int maxi = gcd(grid[1][1], grid[n][m]); // have to be taken anyhow
- for (int i = 1; i * i <= maxi; i++)
- {
- if (maxi % i == 0)
- {
- divisors.pb(i);
- if (i != maxi / i)
- {
- divisors.pb(maxi / i);
- }
- }
- }
- sort(all(divisors), greater<int>());
- for (auto &div : divisors)
- {
- // reset, memset is giving TLE
- for (int i = 1; i <= n; i++)
- {
- for (int j = 1; j <= m; j++)
- {
- dp[i][j] = 0;
- }
- }
- // check if we can reach the end with this gcd
- // base case, initial state true
- dp[1][1] = 1;
- for (int i = 1; i <= n; i++)
- {
- for (int j = 1; j <= m; j++)
- {
- if (!dp[i][j])
- {
- // can't reach here
- continue;
- }
- if (i + 1 <= n && ((grid[i + 1][j] % div) == 0))
- {
- dp[i + 1][j] = 1;
- }
- if (j + 1 <= m && ((grid[i][j + 1] % div) == 0))
- {
- dp[i][j + 1] = 1;
- }
- }
- }
- if (dp[n][m])
- {
- cout << div << endl;
- return;
- }
- }
- cout << -1 << endl;
- return;
- }
- signed main()
- {
- NeedForSpeed;
- int t = 1;
- cin >> t;
- while (t--)
- {
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment