--- /dev/null
+#include <bits/stdc++.h>
+using namespace std;
+
+
+vector<int> get_factors(int n)
+{
+ vector<int> output;
+ for (int i = 1; i < 1 + sqrt(n); i++)
+ {
+ if (n % i == 0)
+ {
+ output.push_back(i);
+ }
+ }
+ return output;
+}
+
+int main()
+{
+ ios_base::sync_with_stdio(false);
+ cin.tie(NULL);
+ int M, N;
+ cin >> M;
+ cin >> N;
+
+ vector<vector<int>> room;
+ int temp;
+
+ for (int i = 0; i < M;i++)
+ {
+ vector<int> v;
+ for (int j = 0; j < N; j++)
+ {
+ cin >> temp;
+ v.push_back(temp);
+ }
+ room.push_back(v);
+ }
+
+ queue<vector<int>> q;
+ q.push({0,0});
+ vector<vector<int>> seen;
+
+ while (!q.empty())
+ {
+ vector<int> current = q.front();
+ q.pop();
+
+ if (find(seen.begin(), seen.end(), current) != seen.end())
+ {
+ continue;
+ }
+ else
+ {
+ seen.push_back(current);
+ }
+
+ int r = current[0];
+ int c = current[1];
+
+ if (r == M -1 && c == N-1)
+ {
+ cout << "yes" << endl;
+ return 0;
+ }
+
+ int n = room[r][c];
+ vector<int> factors = get_factors(n);
+
+
+ for (int i = 0; i < factors.size(); i++)
+ {
+ int row = factors[i] - 1;
+ int col = n / factors[i] - 1;
+ if ( 0 <= row && row < M && 0 <= col && col < N)
+ {
+ q.push({row, col});
+ }
+ if ( 0 <= col && col < M && 0 <= row && row < N)
+ {
+ q.push({col, row});
+ }
+
+ }
+
+
+ }
+ cout << "no" << endl;
+ return 0;
+}
--- /dev/null
+from queue import Queue
+from math import sqrt
+# from functools import lru_cache
+
+
+# @lru_cache()
+def get_factors(n):
+ output = []
+ for i in range(1, 1 + int(sqrt(n))):
+ if n % i == 0:
+ output.append(i)
+ # output.append(n / i)
+ return output
+
+
+M = int(input())
+N = int(input())
+
+room = []
+for i in range(M):
+ room.append(tuple(map(int, input().split())))
+
+q = Queue()
+
+q.put((0, 0))
+
+seen = set()
+
+while not q.empty():
+ r, c = q.get()
+
+ if (r, c) in seen:
+ continue
+ else:
+ seen.add((r, c))
+
+ if r == M - 1 and c == N - 1:
+ print("yes")
+ quit()
+
+ n = room[r][c]
+ for factor in get_factors(n):
+ row, col = int(factor - 1), int(n / factor - 1)
+ if 0 <= row < M and 0 <= col < N:
+ q.put((row, col))
+
+ if 0 <= col < M and 0 <= row < N:
+ q.put((col, row))
+
+
+print("no")